Categories
Python Answers

How to merge lists into a list of tuples with Python?

Spread the love

Sometimes, we want to merge lists into a list of tuples with Python.

In this article, we’ll look at how to merge lists into a list of tuples with Python.

How to merge lists into a list of tuples with Python?

To merge lists into a list of tuples with Python, we can use the zip and list functions.

For instance, we write:

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

We call zip with list_a and list_b to merge the 2 lists together into a iterator with tuples that are each an with an entry from each of the lists.

Then we call list to convert the iterator to a list of tuples.

Therefore, zipped is [(1, 5), (2, 6), (3, 7), (4, 8)].

Conclusion

To merge lists into a list of tuples with Python, we can use the zip and list functions.

By John Au-Yeung

Web developer specializing in React, Vue, and front end development.

Leave a Reply

Your email address will not be published. Required fields are marked *