Conversion of List of Tuples

Alexander Blinne news at blinne.net
Tue Dec 4 10:44:32 CET 2012


Am 03.12.2012 20:58, schrieb subhabangalore at gmail.com:
> Dear Group,
> 
> I have a tuple of list as,
> 
> tup_list=[(1,2), (3,4)]
> Now if I want to covert as a simple list,
> 
> list=[1,2,3,4]
> 
> how may I do that?

Another approach that has not yet been mentioned here:

>>> a=[(1,2), (3,4)]
>>> b=[]
>>> map(b.extend, a)
[None, None]
>>> b
[1, 2, 3, 4]

map returns [None, None] because extend returns nothing, but now
b==[1,2,3,4].

There are more ways:

>>> from operator import add
>>> reduce(add, a)
(1, 2, 3, 4)

or

>>> reduce(operator.add, (list(t) for t in a))
[1, 2, 3, 4]

I didn't do any performance testing, i guess the first one should be
about as fast es the for-loop approach with .extend() and the other two
might be quite slow. Although this only really matters if you have large
lists.

Greetings



More information about the Python-list mailing list