NullException
NullException

Reputation: 4510

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 ?

Upvotes: 2

Views: 1782

Answers (3)

Ashwini Chaudhary
Ashwini Chaudhary

Reputation: 250901

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]

Upvotes: 1

Jon Gauthier
Jon Gauthier

Reputation: 25572

The list call is unnecessary in this case—you're correct.

Some Python methods return iterators rather than lists. The list function can be used to force the iterator to become a list (so that it can be indexed, for example).

Take the function reversed, for example, which returns an iterator:

In [1]: type(reversed([3,1,2]))
Out[1]: listreverseiterator

In [2]: reversed([3,1,2])[1]
---------------------------------------------------------------------------
TypeError: 'listreverseiterator' object has no attribute '__getitem__'

We can use list to consume the iterator and use its results in a list:

In [3]: list(reversed([3,1,2]))[1]
Out[3]: 1

list might be used to force other list-like types to be concrete lists:

In [4]: (1,2,3).append(4)
---------------------------------------------------------------------------
AttributeError: 'tuple' object has no attribute 'append'

In [5]: list((1,2,3)).append(4) # => [1, 2, 3, 4]

Upvotes: 5

Yaniv
Yaniv

Reputation: 1001

Yes, in this case it is unnecessary :-)

Upvotes: -1

Related Questions