In Python, the zip() function is a built-in function that allows you to iterate over multiple sequences (like lists, tuples, or strings) in parallel and access their elements together.
Here's an example of using zip() to iterate over two lists:
fruits = ["apple", "banana", "cherry"]colors = ["red", "yellow", "pink"]for fruit, color in zip(fruits, colors): print(fruit, color) |
In this example, we define two lists called fruits and colors, each containing three elements. We then use the zip() function to iterate over both lists in parallel and access their elements together. Inside the loop, the variables fruit and color take on the values of the corresponding elements in each list.
If the sequences you're iterating over are of different lengths, the zip() function will only iterate up to the length of the shortest sequence. If you want to iterate over all elements of the longest sequence and fill in missing values with a default value, you can use the itertools.zip_longest() function instead.
Here's an example of using zip_longest():
import itertoolsfruits = ["apple", "banana", "cherry"]colors = ["red", "yellow"]for fruit, color in itertools.zip_longest(fruits, colors, fillvalue="unknown"): print(fruit, color) |
In this example, we define two lists called fruits and colors, with colors having one less element than fruits. We then use the zip_longest() function from the itertools module to iterate over both lists and fill in the missing value in colors with the default value "unknown". Inside the loop, the variables fruit and color take on the values of the corresponding elements in each list, with "unknown" being used for the missing value in colors.