Velocity Reviews > Conversion of List of Tuples

# Conversion of List of Tuples

Alexander Blinne
Guest
Posts: n/a

 12-04-2012
Am 03.12.2012 20:58, schrieb http://www.velocityreviews.com/forums/(E-Mail Removed):
> 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:

(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

Hans Mulder
Guest
Posts: n/a

 12-04-2012
On 4/12/12 10:44:32, Alexander Blinne wrote:
> Am 03.12.2012 20:58, schrieb (E-Mail Removed):
>> 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:
>

> (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

Neil Cerutti
Guest
Posts: n/a

 12-04-2012
On 2012-12-04, Hans Mulder <(E-Mail Removed)> wrote:
> It's considered bad style to use map it you don't want the list it
> produces.
>
>> There are more ways:
>>

>> (1, 2, 3, 4)

>
> There's a built-in that does "reduce(operator.add"; it's called "sum":
>
>>>> sum(a, ())

> (1, 2, 3, 4)

I thought that sort of thing would cause a warning. Maybe it's
only for lists.

Here's the recipe from the itertools documentation:

def flatten(listOfLists):
"Flatten one level of nesting"
return chain.from_iterable(listOfLists)

--
Neil Cerutti