During data manipulation with Python , we may need to bring two lists together and equate the elements in each of them pair wise. Which means the element at index 0 from list 1 will be equated with element from index 0 of list2 and so on.
With tuple
The tuple function will be leveraged to take elements form each list in sequence and matching them up. We first store the result in a temp string which has the pattern in which the output of matching up of the values form lists will be displayed.
Example
listA = ['day1', 'day2', 'day3'] listB = ['Mon', 'Tue', 'Fri'] # Given lists print("Given list A is : " ,listA) print("Given list B is : " ,listB) # Pairing list elements temp = len(listA) * '% s = %% s, ' res = temp % tuple(listA) % tuple(listB) # printing result print("Paired lists : " , res)
Output
Running the above code gives us the following result −
Given list A is : ['day1', 'day2', 'day3'] Given list B is : ['Mon', 'Tue', 'Fri'] Paired lists : day1 = Mon, day2 = Tue, day3 = Fri,
With join and zip
The zip function can pair up the elements form lists in sequence and the join function will apply the required pattern we need to apply to the pairs.
Example
listA = ['day1', 'day2', 'day3'] listB = ['Mon', 'Tue', 'Fri'] # Given lists print("Given list A is : " ,listA) print("Given list B is : " ,listB) # Pairing list elements res= ', '.join('% s = % s' % i for i in zip(listA, listB)) # printing result print("Paired lists : " , res)
Output
Running the above code gives us the following result −
Given list A is : ['day1', 'day2', 'day3'] Given list B is : ['Mon', 'Tue', 'Fri'] Paired lists : day1 = Mon, day2 = Tue, day3 = Fri