Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Use list comprehension to build a tuple

Tags:

python

How can I use list comprehension to build a tuple of 2-tuple from a list. It would be equivalent to

tup = () for element in alist:     tup = tup + ((element.foo, element.bar),) 
like image 262
Lim H. Avatar asked Mar 14 '13 13:03

Lim H.


People also ask

How do you create a tuple with a list comprehension?

A tuple comprehension is considered to be less fundamental than a list comprehension. So there is no special syntax dedicated for the same. Yet, if you want a tuple after applying comprehension, it can be achieved by wrapping a tuple around a generator object.

Does list comprehension work for tuples in Python?

There is no tuple comprehension in Python. Comprehension works by looping or iterating over items and assigning them into a container, a Tuple is unable to receive assignments.

Can you turn a list into a tuple?

You can convert a list into a tuple simply by passing to the tuple function.

Can we create a tuple from list in Python?

tuple () function can take any iterable as an argument and convert it into a tuple object. As you wish to convert a python list to a tuple, you can pass the entire list as a parameter within the tuple() function, and it will return the tuple data type as an output.


1 Answers

tup = tuple((element.foo, element.bar) for element in alist) 

Technically, it's a generator expression. It's like a list comprehension, but it's evaluated lazily and won't need to allocate memory for an intermediate list.

For completeness, the list comprehension would look like this:

tup = tuple([(element.foo, element.bar) for element in alist]) 

 

PS: attrgetter is not faster (alist has a million items here):

In [37]: %timeit tuple([(element.foo, element.bar) for element in alist]) 1 loops, best of 3: 165 ms per loop  In [38]: %timeit tuple((element.foo, element.bar) for element in alist) 10 loops, best of 3: 155 ms per loop  In [39]: %timeit tuple(map(operator.attrgetter('foo','bar'), alist)) 1 loops, best of 3: 283 ms per loop  In [40]: getter = operator.attrgetter('foo','bar')  In [41]: %timeit tuple(map(getter, alist)) 1 loops, best of 3: 284 ms per loop  In [46]: %timeit tuple(imap(getter, alist)) 1 loops, best of 3: 264 ms per loop 
like image 93
Pavel Anossov Avatar answered Oct 13 '22 04:10

Pavel Anossov