Python | Preceding element tuples in list
Last Updated :
06 Apr, 2023
Sometimes, while working with Python list, we can have a problem in which we need to construct tuples, with the preceding element, whenever that element matches a particular condition. This can have potential application in day-day programming. Let's discuss a way in which this task can be performed.
Method #1: Using for loop
Python3
# Python3 code to demonstrate working of
# Preceding Tuple elements in list
# initialize list
test_list = [1, 4, 'gfg', 7, 8, 'gfg', 9, 'gfg']
# printing original list
print("The original list is : " + str(test_list))
# initialize ele
ele = 'gfg'
# Preceding Tuple elements in list
res=[]
for i in range(0,len(test_list)):
if(test_list[i]==ele):
res.append((test_list[i-1],test_list[i]))
# printing result
print("Tuple list with desired Preceding elements " + str(res))
OutputThe original list is : [1, 4, 'gfg', 7, 8, 'gfg', 9, 'gfg']
Tuple list with desired Preceding elements [(4, 'gfg'), (8, 'gfg'), (9, 'gfg')]
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 2: Using zip() + list comprehension
This task can be performed using a combination of above functionalities. In this, the zip() performs the task of construction of tuples and the catering of condition matching and iteration is handled by list comprehension.
Python3
# Python3 code to demonstrate working of
# Preceding Tuple elements in list
# using zip() + list comprehension
# initialize list
test_list = [1, 4, 'gfg', 7, 8, 'gfg', 9, 'gfg']
# printing original list
print("The original list is : " + str(test_list))
# initialize ele
ele = 'gfg'
# Preceding Tuple elements in list
# using zip() + list comprehension
res = [(x, y) for x, y in zip(test_list, test_list[1 : ]) if y == ele]
# printing result
print("Tuple list with desired Preceding elements " + str(res))
OutputThe original list is : [1, 4, 'gfg', 7, 8, 'gfg', 9, 'gfg']
Tuple list with desired Preceding elements [(4, 'gfg'), (8, 'gfg'), (9, 'gfg')]
Time Complexity: O(N), where N is the length of the input list test_list.
Auxiliary Space: O(N)
Method 3: Using enumerate
We loop through the original_list using enumerate() function which returns the index and value of each element.
For each element, we check if it is equal to 'gfg' and its index is greater than 0. If it is true, we add a tuple containing the preceding element and the current element to the tuple_list.We use list comprehension to create the tuple_list.
Finally, we print both the original and tuple list.
Python3
# Define two lists of tuples
test_list1 = [(1, 7), (6, 7), (9, 100), (4, 21)]
test_list2 = [(1, 3), (2, 1), (9, 7), (2, 17)]
# Define a function to cross-pair tuples from the two lists
def cross_pairing(test_list1, test_list2):
# Create an empty list to store the cross pairs
result = []
# Loop over each tuple in the first list
for tup1 in test_list1:
# Loop over each tuple in the second list
for tup2 in test_list2:
# If the first element of tup1 is equal to the first element of tup2
if tup1[0] == tup2[0]:
# Cross-pair the second elements of the tuples and append to result
result.append((tup1[1], tup2[1]))
# Return the list of cross pairs
return result
# Call the function and print the result
print(cross_pairing(test_list1, test_list2))
OutputOriginal List : [1, 4, 'gfg', 7, 8, 'gfg', 9, 'gfg']
Tuple List with desired Preceding elements : [(4, 'gfg'), (8, 'gfg'), (9, 'gfg')]
Time complexity: O(n^2), where n is the length of the longer input list. This is because the code iterates over each tuple in test_list1 and each tuple in test_list2, resulting in nested loops that perform n^2 comparisons.
Auxiliary Space: O(n^2), since the output list result can contain up to n^2 cross pairs. Additionally, the memory usage required for storing the input lists is O(n), since each list contains n tuples. Therefore, the total space complexity is O(n^2 + n), which can be simplified to O(n^2) since the n^2 term dominates the space requirements.
Method 4:Using reduce:
Algorithm:
1.Initialize a list test_list and a variable ele.
2.Use a list comprehension to generate a list of tuples, where each tuple contains two consecutive elements of test_list.
3.Filter the list of tuples using an if statement to only include tuples where the second element is equal to ele.
4.Use the reduce function to apply a lambda function to the filtered list of tuples. The lambda function returns a new 5.list that contains all the tuples in the previous list, plus a new tuple that contains the first and second element of the current tuple.
6.The result of the reduce function is a list of tuples containing the desired preceding elements.
Python3
from functools import reduce
test_list = [1, 4, 'gfg', 7, 8, 'gfg', 9, 'gfg']
# printing original list
print("The original list is : " + str(test_list))
ele = 'gfg'
res = reduce(lambda x, y: x + [(y[0], y[1])], [(test_list[i], test_list[i+1]) for i in range(len(test_list)-1) if test_list[i+1] == ele], [])
# printing result
print("Tuple list with desired Preceding elements: ", res)
#This code is contributed by Jyothi pinjala.
OutputThe original list is : [1, 4, 'gfg', 7, 8, 'gfg', 9, 'gfg']
Tuple list with desired Preceding elements: [(4, 'gfg'), (8, 'gfg'), (9, 'gfg')]
Time complexity: O(n), where n is the length of test_list.
Auxiliary Space: O(n), since the list of tuples generated by the list comprehension could potentially be as large as test_list. However, since the reduce function operates on the filtered list of tuples, the actual space complexity of the code may be smaller depending on how many tuples are filtered out by the if statement.
Similar Reads
Python Tutorial - Learn Python Programming Language Python is one of the most popular programming languages. Itâs simple to use, packed with features and supported by a wide range of libraries and frameworks. Its clean syntax makes it beginner-friendly. It'sA high-level language, used in web development, data science, automation, AI and more.Known fo
10 min read
Python Interview Questions and Answers Python is the most used language in top companies such as Intel, IBM, NASA, Pixar, Netflix, Facebook, JP Morgan Chase, Spotify and many more because of its simplicity and powerful libraries. To crack their Online Assessment and Interview Rounds as a Python developer, we need to master important Pyth
15+ min read
Python OOPs Concepts Object Oriented Programming is a fundamental concept in Python, empowering developers to build modular, maintainable, and scalable applications. By understanding the core OOP principles (classes, objects, inheritance, encapsulation, polymorphism, and abstraction), programmers can leverage the full p
11 min read
Python Projects - Beginner to Advanced Python is one of the most popular programming languages due to its simplicity, versatility, and supportive community. Whether youâre a beginner eager to learn the basics or an experienced programmer looking to challenge your skills, there are countless Python projects to help you grow.Hereâs a list
10 min read
Python Exercise with Practice Questions and Solutions Python Exercise for Beginner: Practice makes perfect in everything, and this is especially true when learning Python. If you're a beginner, regularly practicing Python exercises will build your confidence and sharpen your skills. To help you improve, try these Python exercises with solutions to test
9 min read
Python Programs Practice with Python program examples is always a good choice to scale up your logical understanding and programming skills and this article will provide you with the best sets of Python code examples.The below Python section contains a wide collection of Python programming examples. These Python co
11 min read
Python Introduction Python was created by Guido van Rossum in 1991 and further developed by the Python Software Foundation. It was designed with focus on code readability and its syntax allows us to express concepts in fewer lines of code.Key Features of PythonPythonâs simple and readable syntax makes it beginner-frien
3 min read
Python Data Types Python Data types are the classification or categorization of data items. It represents the kind of value that tells what operations can be performed on a particular data. Since everything is an object in Python programming, Python data types are classes and variables are instances (objects) of thes
9 min read
Input and Output in Python Understanding input and output operations is fundamental to Python programming. With the print() function, we can display output in various formats, while the input() function enables interaction with users by gathering input during program execution. Taking input in PythonPython input() function is
8 min read
Enumerate() in Python enumerate() function adds a counter to each item in a list or other iterable. It turns the iterable into something we can loop through, where each item comes with its number (starting from 0 by default). We can also turn it into a list of (number, item) pairs using list().Let's look at a simple exam
3 min read