Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What does the list() function do in Python?

I know that the list() constructor creates a new list but what exactly are its characteristics?

  1. What happens when you call list((1,2,3,4,[5,6,7,8],9))?

  2. What happens when you call list([[[2,3,4]]])?

  3. What happens when you call list([[1,2,3],[4,5,6]])?

From what I can tell, calling the constructor list removes the most outer braces (tuple or list) and replaces them with []. Is this true? What other nuances does list() have?

like image 939
ylun.ca Avatar asked Oct 27 '14 04:10

ylun.ca


2 Answers

list() converts the iterable passed to it to a list. If the itertable is already a list then a shallow copy is returned, i.e only the outermost container is new rest of the objects are still the same.

>>> t = (1,2,3,4,[5,6,7,8],9)
>>> lst = list(t) 
>>> lst[4] is t[4]  #outermost container is now a list() but inner items are still same.
True

>>> lst1 = [[[2,3,4]]]
>>> id(lst1)
140270501696936
>>> lst2 = list(lst1)
>>> id(lst2)
140270478302096
>>> lst1[0] is lst2[0]
True
like image 59
Ashwini Chaudhary Avatar answered Oct 01 '22 05:10

Ashwini Chaudhary


Python has a well-established documentation set for every release version, readable at https://docs.python.org/. The documentation for list() states that list() is merely a way of constructing a list object, of which these are the listed ways:

  • Using a pair of square brackets to denote the empty list: []
  • Using square brackets, separating items with commas: [a], [a, b, c]
  • Using a list comprehension: [x for x in iterable]
  • Using the type constructor: list() or list(iterable)

The list() function accepts any iterable as its argument, and the return value is a list object.

Further reading: https://docs.python.org/3.4/library/stdtypes.html#typesseq-list

like image 23
furkle Avatar answered Oct 01 '22 05:10

furkle