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