Python is a popular, general-purpose programming language that is widely used in various fields. It’s easy to learn and its simple syntax makes it a great language to start with. In this tutorial, we will learn how to zip two lists in Python.
Steps:
1. Create two lists.
In order to zip two lists together, we need two lists. Let’s create two lists named “list1” and “list2” containing some elements.
1 2 |
list1 = ["a", "b", "c"] list2 = [1, 2, 3] |
2. Use the built-in zip function.
Python has a built-in function called zip, which is used to combine two or more iterables into a single iterable object. Let’s use this function to combine the two lists we created.
1 |
zipped = zip(list1, list2) |
3. Convert the zipped object into a list.
The “zipped” object we created using the zip function is a zip object. In order to view the contents of this object, we need to convert it into a list.
1 |
result = list(zipped) |
Note: We can also convert it into a dictionary, tuple, or set instead of a list.
4. Print the result.
Finally, let’s print the result to see how the two lists are zipped together.
1 |
print(result) |
The output should be as follows:
[('a', 1), ('b', 2), ('c', 3)]
Conclusion:
In this tutorial, we learned how to zip two lists in Python using the built-in zip function. We created two lists, used the zip function to combine them, converted the result into a list, and finally printed the result.
Full Code:
1 2 3 4 5 6 7 8 |
list1 = ["a", "b", "c"] list2 = [1, 2, 3] zipped = zip(list1, list2) result = list(zipped) print(result) |