PythonBuilt-in functions
list()
Creates a list, either empty or from the items of another iterable.
- Returns
- A new list.
Example
#Python
print(list("code"))
print(list(range(4)))
print(list({"html": 11, "css": 9}))
print(list())Resultsaved result, you can check it
['c', 'o', 'd', 'e']
[0, 1, 2, 3]
['html', 'css']
[]
Definition and usage
#The list() function with no argument creates an empty list. With an argument, it converts any iterable to a list: a string (a list of characters), a tuple, a set, a range, dictionary keys, or a generator.
It also creates a shallow copy of an existing list: copy = list(original). Changing the copy doesn't change the original, but nested objects inside it are shared.
To build a list while transforming its items, a list comprehension is usually more readable than list(map(...)).
Syntax
#Syntax
list()
list(iterable)Parameters
#iterable
optional
The object whose items become the new list.
More examples
#Python
original = ["HTML", "CSS"]
copy = list(original)
copy.append("JavaScript")
print(original)
print(copy)Resultsaved result, you can check it
['HTML', 'CSS']
['HTML', 'CSS', 'JavaScript']
Good practices
#- Create an empty list with
[]. That is shorter and faster thanlist(). - Unique items in a list while keeping order:
list(dict.fromkeys(items)).
Related entries
#- list vs tuplelist is a mutable sequence you can modify, while tuple is an immutable sequence that can be a dictionary key or a set element.
- tuple()Creates a tuple: an immutable sequence of items.
- set()Creates a set: an unordered collection of unique items.
- list.append()Adds one item to the end of a list.
- List comprehensionsA concise way to build lists, sets, and dictionaries from other collections.
Spotted a mistake or missing an example? Write to us.