Yes, you can also use the unpacking operator * with zip() to unpack the elements of each sequence into separate variables.
Here's an example of using zip() with unpacking:
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 with unpacking 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.
Note that you can also use the * operator to unpack multiple sequences at once:
fruits = ["apple", "banana", "cherry"]colors = ["red", "yellow", "pink"]prices = [0.5, 0.4, 0.3]for fruit, color, price in zip(fruits, colors, prices): print(fruit, color, price) |
In this example, we define three lists called fruits, colors, and prices, each containing three elements. We then use the zip() function with unpacking to iterate over all three lists in parallel and access their elements together. Inside the loop, the variables fruit, color, and price take on the values of the corresponding elements in each list.