Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
-
Economics & Finance
Equate two list index elements in Python
During data manipulation with Python, we may need to bring two lists together and equate the elements in each of them pair wise. This means the element at index 0 from list 1 will be equated with element from index 0 of list 2 and so on.
Using Tuple Formatting
The tuple function can be leveraged to take elements from each list in sequence and match 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 from lists will be displayed ?
Example
list_a = ['day1', 'day2', 'day3']
list_b = ['Mon', 'Tue', 'Fri']
# Given lists
print("Given list A is :", list_a)
print("Given list B is :", list_b)
# Pairing list elements
temp = len(list_a) * '%s = %s, '
res = temp % (tuple(list_a) + tuple(list_b))
# printing result
print("Paired lists :", res)
Given list A is : ['day1', 'day2', 'day3'] Given list B is : ['Mon', 'Tue', 'Fri'] Paired lists : day1 = Mon, day2 = Tue, day3 = Fri,
Using Join and Zip
The zip() function can pair up the elements from lists in sequence and the join() function will apply the required pattern we need to apply to the pairs ?
Example
list_a = ['day1', 'day2', 'day3']
list_b = ['Mon', 'Tue', 'Fri']
# Given lists
print("Given list A is :", list_a)
print("Given list B is :", list_b)
# Pairing list elements
res = ', '.join(f'{x} = {y}' for x, y in zip(list_a, list_b))
# printing result
print("Paired lists :", res)
Given list A is : ['day1', 'day2', 'day3'] Given list B is : ['Mon', 'Tue', 'Fri'] Paired lists : day1 = Mon, day2 = Tue, day3 = Fri
Using List Comprehension
A more Pythonic approach is to use list comprehension with zip() to create key-value pairs ?
Example
list_a = ['day1', 'day2', 'day3']
list_b = ['Mon', 'Tue', 'Fri']
# Given lists
print("Given list A is :", list_a)
print("Given list B is :", list_b)
# Creating pairs as list of strings
pairs = [f"{x} = {y}" for x, y in zip(list_a, list_b)]
print("Paired elements as list:", pairs)
# Join them into a single string
result = ', '.join(pairs)
print("Paired lists :", result)
Given list A is : ['day1', 'day2', 'day3'] Given list B is : ['Mon', 'Tue', 'Fri'] Paired elements as list: ['day1 = Mon', 'day2 = Tue', 'day3 = Fri'] Paired lists : day1 = Mon, day2 = Tue, day3 = Fri
Comparison
| Method | Readability | Python Version | Best For |
|---|---|---|---|
| Tuple formatting | Complex | Python 2/3 | Legacy code |
| Join + Zip | Good | Python 3 | Simple pairing |
| List comprehension | Excellent | Python 3 | Most scenarios |
Conclusion
Use zip() with f-strings and join() for the most readable approach. List comprehension provides flexibility when you need to process pairs further before joining them into a string.
