To combine two lists element-wise in Python, you can use the
zip() function along with a list comprehension. The
zip() function pairs up corresponding elements from the two lists, and the list comprehension allows you to create a new list by combining those pairs. Here’s an example:
list1 = [1, 2, 3] list2 = [4, 5, 6] combined_list = [x + y for x, y in zip(list1, list2)] print(combined_list)
In this example, we have
list2, each containing numeric elements. We use
zip(list1, list2) to pair up corresponding elements from both lists. The list comprehension
[x + y for x, y in zip(list1, list2)] creates a new list by summing up each pair of elements obtained from
zip(). The resulting
combined_list will contain the combined values
[5, 7, 9].
Note that the lists provided to
zip() should have the same length. If the lists have different lengths, the resulting combined list will have a length equal to the shortest list. Any remaining elements in the longer list will be ignored.
By using the
zip() function and a list comprehension, you can efficiently combine two lists element-wise to create a new list based on a specific operation or logic.