To merge multiple lists into a single list of tuples, where each tuple consists of corresponding elements from the original lists, Python offers a versatile solution using the zip() function.
In Python 2, the code would be:
list_a = [1, 2, 3, 4] list_b = [5, 6, 7, 8] list_c = zip(list_a, list_b)
In Python 3, to convert the result to a list, the code would be:
list_a = [1, 2, 3, 4] list_b = [5, 6, 7, 8] list_c = list(zip(list_a, list_b))
The zip() function takes multiple iterables (in this case, list_a and list_b) and returns an iterator of tuples. Each tuple contains the elements from the corresponding positions in the iterables. Thus, if list_a has n elements and list_b has m elements, the resulting iterator will have either min(n, m) tuples or an empty iterator if one of the lists is empty.
The above is the detailed content of How to Efficiently Combine Multiple Python Lists into a List of Tuples?. For more information, please follow other related articles on the PHP Chinese website!