Open In App

Python | Equate two list index elements

Last Updated : 26 Apr, 2023
Improve
Improve
Like Article
Like
Save
Share
Report

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


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:

  1. Import the reduce function from the functools module.
  2. Initialize the two lists.
  3. Print the original lists.
  4. Use reduce() function to equate two list index elements:
  5. Create a list comprehension using zip() and string formatting to create a list of paired elements strings.
  6. Pass the above list and a lambda function to reduce() that concatenates the two elements with ‘, ‘ as a separator.
  7. 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.


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)  # add quotes around digits
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.



Like Article
Suggest improvement
Previous
Next
Share your thoughts in the comments

Similar Reads