I have two lists and want to merges them into one list of tuples
. I want to do it with list comprehension
, I can get it working using map
. but would be nice to know how list comprehension here will work.
code here
>>> lst = [1,2,3,4,5]
>>> lst2 = [6,7,8,9,10]
>>> tup = map(None,lst,lst2) # works fine
>>> tup
[(1, 6), (2, 7), (3, 8), (4, 9), (5, 10)]
>>> l3 = [lst, lst2]
>>> l3
[[1, 2, 3, 4, 5], [6, 7, 8, 9, 10]]
>>> zip(*l3) # works fine
[(1, 6), (2, 7), (3, 8), (4, 9), (5, 10)]
>>> [(i,j) for i in lst and for j in lst2] # does not work
File "<stdin>", line 1
[(i,j) for i in lst and for j in lst2]
^
SyntaxError: invalid syntax
>>>
I have written comments where it works and where it does not. How can a two for-loop
be coupled in list comprehension
If you're in a hurry, here's the short answer: use the list comprehension statement [tuple(x) for x in list] to convert each element in your list to a tuple. This works also for list of lists with varying number of elements.
This is the power of list comprehension. It can identify when it receives a string or a tuple and work on it like a list. You can do that using loops. However, not every loop can be rewritten as list comprehension.
There is no tuple comprehension in Python, but you can get the desired result by using a generator expression and converting the generator object to a tuple, e.g. my_tuple = tuple(int(element) for element in ('1', '3', '5')) .
1) Using tuple() builtin function tuple () function can take any iterable as an argument and convert it into a tuple object. As you wish to convert a python list to a tuple, you can pass the entire list as a parameter within the tuple() function, and it will return the tuple data type as an output.
Think about list comprehensions as loops. How can you write 2 not nested loops?
You can do this with somewhat wierd list comprehension:
[(x, lst2[i]) for i, x in enumerate(lst)]
or
[(lst[i], lst2[i]) for i in xrange(len(lst))]
But actually, it's better to use zip
.
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