Skip to content
Tutorials Center
My learning

Topics

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.

Python
print(list("abc"))        # ['a', 'b', 'c']
print(list(range(3)))     # [0, 1, 2]

Try it

Python Building lists

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.

Python Copies, nesting and generators

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

Python
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 to a.copy() and a[:]: the outer list is new, but nested lists and dicts are shared. Use copy.deepcopy() for independent nested data.
  • Dictionaries give their keys. Use list(d.values()) or list(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; use sorted() when order matters.
  • Large or infinite iterables. list(itertools.count()) never ends and eats memory. Slice lazily with itertools.islice().
  • Literal vs call. [] is slightly faster than list() for an empty list; [*iterable] is another way to unpack into a list.
  • Don't shadow it. Naming a variable list breaks later calls to list(...).
  • Subclassing. class Stack(list) works, but composition is often clearer.