NullException NullException - 2 months ago 6
Python Question

Python list tuples

Say,

data = { 123: 1, 234: 2, 241: 4 }
a = list(sorted(data.items()))


Isn't list unnecessary ? I think,
sorted(data.items())
itself will return
list
of
tuples
? Why would anyone use list function specifically ?

Answer

Yes, sorted returns a list itself. So, calling list() on a list data structure is useless. Calling list() on it is equivalent to sorted(data.items())[:].

In [7]: print sorted.__doc__
sorted(iterable, cmp=None, key=None, reverse=False) --> new sorted list

In [8]: lis=[1,2,3]

In [9]: lis
Out[9]: [1, 2, 3]

In [10]: list(lis)    #same result, but different object. (A shallow copy)
Out[10]: [1, 2, 3]

list() can be useful if you want to fetch all the values of an iterator :

In [11]: y=xrange(5)

In [12]: y
Out[12]: xrange(5)

In [13]: list(y)
Out[13]: [0, 1, 2, 3, 4]