Python Reference ยท Built-in Functions
Python list() function
Reference for Python list(): create an empty list or build one from any iterable, shallow copies, strings, dict keys, ranges and the nested-list pitfall.
list is the built-in mutable sequence type, and calling list() creates a new list. With no argument it returns an empty list; with an iterable it builds a list containing the iterable's items in order.
Use list() to turn something lazy or unordered into a concrete list: a range, the output of map() or filter(), the keys of a dictionary, the characters of a string. It also makes a quick shallow copy of an existing list.
print(list("abc")) # ['a', 'b', 'c'] print(list(range(3))) # [0, 1, 2]
Try it
Press Run (or Ctrl + Enter) to see the result here.
Program input ยท what you'd type while the program runs
Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.
Press Run (or Ctrl + Enter) to see the result here.
Program input ยท what you'd type while the program runs
Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.
Syntax
list() list(iterable)
| Name | Description |
|---|---|
iterable |
Optional. Any iterable: a sequence, set, dict, generator, file, or an object with __iter__(). |
Return value: a new list. The items are the same objects as in the iterable (no deep copy).
Raises: TypeError if the argument is not iterable. Errors raised while iterating pass through.
Usage notes
- Shallow copy.
list(a)is equivalent toa.copy()anda[:]: the outer list is new, but nested lists and dicts are shared. Usecopy.deepcopy()for independent nested data. - Dictionaries give their keys. Use
list(d.values())orlist(d.items())for values or pairs. - Strings give single characters, not words. Use
str.split()for words. - Iterators are consumed.
list(it)uses up the iterator, so a second call returns[]. - Sets are unordered.
list(some_set)has no guaranteed order; usesorted()when order matters. - Large or infinite iterables.
list(itertools.count())never ends and eats memory. Slice lazily withitertools.islice(). - Literal vs call.
[]is slightly faster thanlist()for an empty list;[*iterable]is another way to unpack into a list. - Don't shadow it. Naming a variable
listbreaks later calls tolist(...). - Subclassing.
class Stack(list)works, but composition is often clearer.
Related
tuple(),set(),dict(),sorted(),range()list.append(),list.copy(),list.sort(), list comprehensions- Lessons: Lists, List methods