Python | Equate two list index elements
Last Updated :
26 Apr, 2023
Sometimes we need to link two list from the point of view of their index elements and this kind of problem comes mostly in places where we need to display in formatted form the linkage of two lists with one another. This a very specific problem, but can be useful whenever we need a possible solution. Let's discuss certain ways in which this can be done.
Method #1 : Using formatting + tuple() The string formatting can be used to specify the way we need to output the list and the task of pairing the like indices can be done with the help of tuple function.
Python3
# Python3 code to demonstrate
# Equate two list index elements
# using formatting + tuple()
# initializing lists
test_list1 = ['GeeksforGeeks', 'is', 'best']
test_list2 = ['1', '2', '3']
# printing original lists
print("The original list 1 is : " + str(test_list1))
print("The original list 2 is : " + str(test_list2))
# using formatting + tuple() to
# Equate two list index elements
temp = len(test_list1) * '% s = %% s, '
res = temp % tuple(test_list1) % tuple(test_list2)
# printing result
print ("The paired elements string is : " + res)
Output : The original list 1 is : ['GeeksforGeeks', 'is', 'best']
The original list 2 is : ['1', '2', '3']
The paired elements string is : GeeksforGeeks = 1, is = 2, best = 3,
Time Complexity: O(n*n), where n is the length of the input list. This is because we’re using formatting + tuple() which has a time complexity of O(n*n) in the worst case.
Auxiliary Space: O(n), as we’re using additional space res other than the input list itself with the same size of input list
Method #2 : Using join() + zip() These two methods can also combine to achieve this particular task, the join function can be used to extend the format logic to all indices and construct a string, zip function pairs the like index elements from both the tuples.
Python3
# Python3 code to demonstrate
# Equate two list index elements
# using join() + zip()
# initializing lists
test_list1 = ['GeeksforGeeks', 'is', 'best']
test_list2 = ['1', '2', '3']
# printing original lists
print("The original list 1 is : " + str(test_list1))
print("The original list 2 is : " + str(test_list2))
# using join() + zip() to
# Equate two list index elements
res = ', '.join('% s = % s' % i for i in zip(test_list1, test_list2))
# printing result
print ("The paired elements string is : " + res)
Output : The original list 1 is : ['GeeksforGeeks', 'is', 'best']
The original list 2 is : ['1', '2', '3']
The paired elements string is : GeeksforGeeks = 1, is = 2, best = 3,
Time Complexity: O(n*n), where n is the length of the list test_list
Auxiliary Space: O(n) additional space of size n is created where n is the number of elements in the res list
Method #3 : Using fstrings + looping
One other approach you could use is to use a for loop to iterate through the elements of the lists and use fstring to build the resulting string. For example:
Python3
def equate_lists(lst1, lst2):
# Initialize the result string
result = ""
# Iterate through the elements of the lists
for x, y in zip(lst1, lst2):
# Concatenate the current element of the first list, an equal sign,
# and the current element of the second list, separated by a comma
result += f"{x}={y}, "
# Return the resulting string
return result
# Test the function
print(equate_lists(['GeeksforGeeks', 'is', 'best'], ['1', '2', '3'])) # Output: "GeeksforGeeks=1, is=2, best=3, "
print(equate_lists(['a', 'b', 'c'], ['x', 'y', 'z'])) # Output: "a=x, b=y, c=z, "
#This code is contributed by Edula Vinay Kumar Reddy
OutputGeeksforGeeks=1, is=2, best=3,
a=x, b=y, c=z,
The time complexity of the approach using a for loop and string concatenation to equate the elements of two lists is O(n), where n is the length of the lists. This is because the loop iterates through the elements of the lists and performs a constant amount of work (concatenating the current elements) for each element.
The space complexity of this approach is also O(n), because the resulting string has a length proportional to the length of the lists. This is because each element of the lists is concatenated to the result string, which grows linearly with the size of the lists.
Method #4 : Using reduce():
Algorithm:
- Import the reduce function from the functools module.
- Initialize the two lists.
- Print the original lists.
- Use reduce() function to equate two list index elements:
- Create a list comprehension using zip() and string formatting to create a list of paired elements strings.
- Pass the above list and a lambda function to reduce() that concatenates the two elements with ', ' as a separator.
- Print the result.
Python3
# Python3 code to demonstrate
# Equate two list index elements
# using reduce()
from functools import reduce
# initializing lists
test_list1 = ['GeeksforGeeks', 'is', 'best']
test_list2 = ['1', '2', '3']
# printing original lists
print("The original list 1 is : " + str(test_list1))
print("The original list 2 is : " + str(test_list2))
# using reduce() to
# Equate two list index elements
res = reduce(lambda a, b: a + ', ' + b, ['%s = %s' % i for i in zip(test_list1, test_list2)])
# printing result
print("The paired elements string is : " + res)
#This code is contributed by Rayudu.
OutputThe original list 1 is : ['GeeksforGeeks', 'is', 'best']
The original list 2 is : ['1', '2', '3']
The paired elements string is : GeeksforGeeks = 1, is = 2, best = 3
Time Complexity:
The join() function has a time complexity of O(n), where n is the length of the resulting string.
The zip() function has a time complexity of O(n), where n is the length of the smaller of the two input lists.
The list comprehension has a time complexity of O(n), where n is the length of the smaller of the two input lists.
Therefore, the overall time complexity of the code is O(n).
Space Complexity:
The space complexity of the code depends on the size of the input lists and the resulting string.
The join() function creates a new string that is the same length as the combined length of the input lists, so its space complexity is O(n).
The zip() function creates a new list that is the same length as the smaller of the two input lists, so its space complexity is O(min(n1, n2)).
The list comprehension creates a new list that is the same length as the smaller of the two input lists, so its space complexity is also O(min(n1, n2)).
Therefore, the overall space complexity of the code is O(n), where n is the combined length of the input lists.
METHOD 5:Using re method .
APPROACH:
This code creates a string result by joining together the corresponding elements of list1 and list2 with the format "{x} = {y}". It then uses a regular expression to add single quotes around any digits in the string, which will convert the numeric values in list2 to string literals. Finally, it prints the modified result string.
ALGORITHM:
1.Create two lists, list1 and list2, containing some string and numeric values respectively.
2.Use zip function to create an iterable of tuples, where each tuple contains a corresponding pair of elements from list1 and list2.
3.Use a list comprehension to format each pair of elements as a string in the format "{x} = {y}".
4.Join the resulting list of strings together with commas using join method to create a single string.
5.Use re.sub method with a regular expression pattern to add single quotes around any digits in the string.
6.Print the modified string.
Python3
import re
list1 = ['GeeksforGeeks', 'is', 'best']
list2 = ['1', '2', '3']
result = ", ".join([f"{x} = {y}" for x, y in zip(list1, list2)])
result = re.sub(r"\b(\d+)\b", r"'\1'", result) # add quotes around digits
print(result)
OutputGeeksforGeeks = '1', is = '2', best = '3'
Time complexity:
1.Creating the tuples using zip function requires O(n) time, where n is the length of the shortest input list.
2.The list comprehension creates a new list with the same length as the shortest input list, which takes O(n) time.
3.Joining the list of strings together with commas takes O(n) time.
4.The regular expression substitution using re.sub function takes O(n) time in the worst case, where n is the length of the input string.
5.Therefore, the overall time complexity of this code is O(n).
Space complexity:
This code uses O(n) extra space to store the output list and string, where n is the length of the shortest input list.
Similar Reads
Add Elements of Two Lists in Python
Adding corresponding elements of two lists can be useful in various situations such as processing sensor data, combining multiple sets of results, or performing element-wise operations in scientific computing. List Comprehension allows us to perform the addition in one line of code. It provides us a
3 min read
Python | Equidistant element list
Sometimes, while working with Python list we can have a problem in which we need to construct the list in which the range is auto computed using the start, end and length parameters. The solution of this problem can have many applications. Let's discuss a way in which this task can be performed. Met
2 min read
Python - Similar index elements frequency
Sometimes, while working with Python list, we can have a problem in which we need to check if one element has similar index occurrence in other list. This can have possible application in many domains. Lets discuss certain ways in which this task can be performed. Method #1 : Using sum() + zip() The
7 min read
Python | Extract similar index elements
Sometimes, while working with Python data, we can have a problem in which we require to extract the values across multiple lists which are having similar index values. This kind of problem can come in many domains. Let's discuss certain ways in which this problem can be solved. Method #1 : Using loo
6 min read
Python - Index Ranks of Elements
Given a list of elements, our task is to get the index ranks of each element. Index Rank of Number = (Sum of occurrence indices of number) / number Input : test_list = [3, 4, 6, 5, 3, 4, 9, 1, 2, 1, 8, 3, 2, 3, 9] Output : [(1, 16.0), (2, 10.0), (3, 9.333333333333334), (4, 1.5), (5, 0.6), (6, 0.3333
3 min read
Difference between two Lists in Python
The difference between two lists in Python refers to the elements that are present in one list but not in the other. For example, finding the difference between lists a = [1, 2, 3, 4] and b = [3, 4, 5, 6] can result in [1, 2] by removing the common elements (3 and 4).Using setSet operations are most
3 min read
Python - Elements with same index
Given a List, get all elements that are at their index value. Input : test_list = [3, 1, 8, 5, 4, 10, 6, 9]Â Output : [1, 4, 6]Â Explanation : These elements are at same position as its number.Input : test_list = [3, 10, 8, 5, 14, 10, 16, 9]Â Output : []Â Explanation : No number at its index. Method
5 min read
Python - Product of elements using Index list
Accessing an element from its index is easier task in python, just using the [] operator in a list does the trick. But in certain situations we are presented with tasks when we have more than once indices and we need to get all the elements corresponding to those indices and then perform the multipl
7 min read
Python - Get Indices of Even Elements from list
Sometimes, while working with Python lists, we can have a problem in which we wish to find Even elements. This task can occur in many domains such as web development and while working with Databases. We might sometimes, require to just find the indices of them. Let us discuss certain ways to find in
8 min read
Python - Negative index of Element in List
We are given a list we need to find the negative index of that element. For example, we are having a list li = [10, 20, 30, 40, 50] and the given element is 30 we need to fin the negative index of it so that given output should be -3.Using index()index() method in Python searches for the first occur
3 min read