Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to merge lists into a list of tuples?

What is the Pythonic approach to achieve the following?

# Original lists:  list_a = [1, 2, 3, 4] list_b = [5, 6, 7, 8]  # List of tuples from 'list_a' and 'list_b':  list_c = [(1,5), (2,6), (3,7), (4,8)] 

Each member of list_c is a tuple, whose first member is from list_a and the second is from list_b.

like image 962
rubayeet Avatar asked Mar 09 '10 07:03

rubayeet


People also ask

How do I combine lists into tuples?

The most Pythonic way to merge multiple lists l0, l1, ..., ln into a list of tuples (grouping together the i -th elements) is to use the zip() function zip(l0, l1, ..., ln) . If you store your lists in a list of lists lst , write zip(*lst) to unpack all inner lists into the zip function.

How do I merge two lists into a list in Python?

In python, we can use the + operator to merge the contents of two lists into a new list. For example, We can use + operator to merge two lists i.e. It returned a new concatenated lists, which contains the contents of both list_1 and list_2.

Can you make a list of tuples?

We can create a list of tuples i.e. the elements of the tuple can be enclosed in a list and thus will follow the characteristics in a similar manner as of a Python list. Since, Python Tuples utilize less amount of space, creating a list of tuples would be more useful in every aspect.


1 Answers

In Python 2:

>>> list_a = [1, 2, 3, 4] >>> list_b = [5, 6, 7, 8] >>> zip(list_a, list_b) [(1, 5), (2, 6), (3, 7), (4, 8)] 

In Python 3:

>>> list_a = [1, 2, 3, 4] >>> list_b = [5, 6, 7, 8] >>> list(zip(list_a, list_b)) [(1, 5), (2, 6), (3, 7), (4, 8)] 
like image 52
YOU Avatar answered Oct 03 '22 05:10

YOU