list() in python

The list() and tuple() methods take sequence types and convert them to lists and tuples, respectively. Although strings are also sequence types, they are not commonly used with list() and tuple(). These built-in functions are used more often to convert from one type to the other., i.e., when you have a tuple that you need to make a list (so that you can modify its elements) and vice versa.


>>> aList = ['tao',93,99,'time']
>>> aTuple = tuple(aList)
>>> print aList
['tao', 93, 99, 'time']
>>> print aTuple
('tao', 93, 99, 'time')
>>> back2aList = list(aTuple)
>>> back2aList == aList
>>> back2aList is aList

Neither list() nor tuple() performs true conversions. In other words, the list you passed to tuple() does not turn into a list, and the tuple you give to list() does not really become a list. Instead, these built-in functions create a new object of the destination type and populate it with the same elements as the original sequence. In the last two examples above, although the data set for both lists is the same (hence satisfying ==), neither variable points to the same list (thus failing is).


You may also like...