So, I have x=[(12,), (1,), (3,)]
(list of tuples) and I want x=[12, 1, 3]
(list of integers) in best way possible? Can you please help?
You didn't say what you mean by "best", but presumably you mean "most pythonic" or "most readable" or something like that.
The list comprehension given by F3AR3DLEGEND is probably the simplest. Anyone who knows how to read a list comprehension will immediately know what it means.
y = [i[0] for i in x]
However, often you don't really need a list, just something that can be iterated over once. If you've got a billion elements in x
, building a billion-element y
just to iterate over it one element at a time may be a bad idea. So, you can use a generator expression:
y = (i[0] for i in x)
If you prefer functional programming, you might prefer to use map
. The downside of map
is that you have to pass it a function, not just an expression, which means you either need to use a lambda
function, or itemgetter
:
y = map(operator.itemgetter(0), x)
In Python 3, this is equivalent to the generator expression; if you want a list
, pass it to list
. In Python 2, it returns a list
; if you want an iterator, use itertools.imap
instead of map
.
If you want a more generic flattening solution, you can write one yourself, but it's always worth looking at itertools
for generic solutions of this kind, and there is in fact a recipe called flatten
that's used to "Flatten one level of nesting". So, copy and paste that into your code (or pip install more-itertools
) and you can just do this:
y = flatten(x)
If you look at how flatten
is implemented, and then at how chain.from_iterable
is implemented, and then at how chain
is implemented, you'll notice that you could write the same thing in terms of builtins. But why bother, when flatten
is going to be more readable and obvious?
Finally, if you want to reduce the generic version to a nested list comprehension (or generator expression, of course):
y = [j for i in x for j in i]
However, nested list comprehensions are very easy to get wrong, both in writing and reading. (Note that F3AR3DLEGEND, the same person who gave the simplest answer first, also gave a nested comprehension and got it wrong. If he can't pull it off, are you sure you want to try?) For really simple cases, they're not too bad, but still, I think flatten
is a lot easier to read.
y = [i[0] for i in x]
This only works for one element per tuple, though.
However, if you have multiple elements per tuple, you can use a slightly more complex list comprehension:
y = [i[j] for i in x for j in range(len(i))]
Reference: List Comprehensions
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