Conversion of List of Tuples
Hans Mulder
hansmu at xs4all.nl
Tue Dec 4 06:45:06 EST 2012
On 4/12/12 10:44:32, Alexander Blinne wrote:
> 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].
It's considered bad style to use map it you don't want the list it
produces.
> There are more ways:
>
>>>> from operator import add
>>>> reduce(add, a)
> (1, 2, 3, 4)
There's a built-in that does "reduce(operator.add"; it's called "sum":
>>> sum(a, ())
(1, 2, 3, 4)
>>>
> or
>
>>>> reduce(operator.add, (list(t) for t in a))
> [1, 2, 3, 4]
This is a valid use case for the map operator:
>>> sum(map(list, a), [])
[1, 2, 3, 4]
>>>
> I didn't do any performance testing, i guess the first one should be
> about as fast as the for-loop approach with .extend() and the other two
> might be quite slow. Although this only really matters if you have large
> lists.
Hope this helps,
-- HansM
More information about the Python-list
mailing list