Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

how to get tuples from lists using list comprehension in python

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

like image 910
eagertoLearn Avatar asked Sep 24 '13 19:09

eagertoLearn


People also ask

How do you convert a list of lists to tuples?

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.

Does list comprehension work with tuples?

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.

Can you do tuple comprehension in Python?

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')) .

How do I turn a list into a tuple in Python?

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.


1 Answers

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.

like image 146
Roman Pekar Avatar answered Oct 19 '22 23:10

Roman Pekar