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
test_list1 = [ 'GeeksforGeeks' , 'is' , 'best' ]
test_list2 = [ '1' , '2' , '3' ]
print ("The original list 1 is : " + str (test_list1))
print ("The original list 2 is : " + str (test_list2))
temp = len (test_list1) * '% s = %% s, '
res = temp % tuple (test_list1) % tuple (test_list2)
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
test_list1 = [ 'GeeksforGeeks' , 'is' , 'best' ]
test_list2 = [ '1' , '2' , '3' ]
print ("The original list 1 is : " + str (test_list1))
print ("The original list 2 is : " + str (test_list2))
res = ', ' .join( '% s = % s' % i for i in zip (test_list1, test_list2))
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):
result = ""
for x, y in zip (lst1, lst2):
result + = f "{x}={y}, "
return result
print (equate_lists([ 'GeeksforGeeks' , 'is' , 'best' ], [ '1' , '2' , '3' ]))
print (equate_lists([ 'a' , 'b' , 'c' ], [ 'x' , 'y' , 'z' ]))
|
Output
GeeksforGeeks=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
from functools import reduce
test_list1 = [ 'GeeksforGeeks' , 'is' , 'best' ]
test_list2 = [ '1' , '2' , '3' ]
print ( "The original list 1 is : " + str (test_list1))
print ( "The original list 2 is : " + str (test_list2))
res = reduce ( lambda a, b: a + ', ' + b, [ '%s = %s' % i for i in zip (test_list1, test_list2)])
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:
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)
print (result)
|
Output
GeeksforGeeks = '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
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 - Extract Elements from Ranges in List
We are given a list and list containing tuples we need to extract element from ranges in tuples list. For example, n = [10, 20, 30, 40, 50, 60, 70, 80, 90] and r = [(1, 3), (5, 7)] (ranges) we need to extract elements so that output should be [[20, 30, 40], [60, 70, 80]]. Using List ComprehensionLis
3 min read
Python - Index Ranks of Elements
Given a list of elements, our task is to get the index ranks of each element. [Tex]Index Rank of Number = (Sum of occurrence indices of number) / number[/Tex] 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),
3 min read
Python - Move Element to End of the List
We are given a list we need to move particular element to end to the list. For example, we are given a list a=[1,2,3,4,5] we need to move element 3 at the end of the list so that output list becomes [1, 2, 4, 5, 3]. Using remove() and append()We can remove the element from its current position and t
3 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 occu
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 #1:
5 min read
Element indices Summation - Python
Our task is to calculate the sum of elements at specific indices in a list. This means selecting elements at specific positions and computing their sum. Given a list and a set of indices, the goal is to compute the sum of elements present at those indices. For example, given the list [10, 20, 30, 40
3 min read
Python | Record elements Average in List
Given a list of tuples, write a program to find average of similar tuples in list. Examples: Input: [('Geeks', 10), ('For', 10), ('Geeks', 2), ('For', 9), ('Geeks', 10)] Output: Resultant list of tuples: [('For', 9.5), ('Geeks', 7.333333333333333)] Input: [('Akshat', 10), ('Garg', 10), ('Akshat', 2)
3 min read