I have the following lists of lists:
animals = [('dog', 'cat'), ('mouse', 'bird')]
I would like to reduce it to:
animals = ['dog', 'cat', 'mouse', 'bird']
is there a simpler way to have the result above than doing something like this:
animals = [('dog', 'cat'), ('mouse', 'bird')]
final = []
for a in animals:
final.append(a[0])
final.append(a[1])
print final
You can use itertools.chain.from_iterable:
>>> from itertools import chain
>>> list(chain.from_iterable(animals))
['dog', 'cat', 'mouse', 'bird']
Or a nested list comprehension:
>>> [anim for item in animals for anim in item]
['dog', 'cat', 'mouse', 'bird']
For tiny list use the list comprehension version, otherwise use itertools.chain.from_iterable.
>>> animals = [('dog', 'cat'), ('mouse', 'bird')]
>>> %timeit list(chain.from_iterable(animals))
100000 loops, best of 3: 2.31 us per loop
>>> %timeit [anim for item in animals for anim in item]
1000000 loops, best of 3: 1.13 us per loop
>>> animals = [('dog', 'cat'), ('mouse', 'bird')]*100
>>> %timeit list(chain.from_iterable(animals))
10000 loops, best of 3: 31.5 us per loop
>>> %timeit [anim for item in animals for anim in item]
10000 loops, best of 3: 73.7 us per loop
>>> animals = [('dog', 'cat'), ('mouse', 'bird')]*1000
>>> %timeit list(chain.from_iterable(animals))
1000 loops, best of 3: 296 us per loop
>>> %timeit [anim for item in animals for anim in item]
1000 loops, best of 3: 733 us per loop
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With