Python - Extract element from list succeeded by K
Last Updated :
10 May, 2023
Given a list, extract the elements which are having K as the next element.
Input : test_list = [2, 3, 5, 7, 8, 5, 3, 5], K = 3
Output : [2, 5]
Explanation : Elements before 3 are 2, 5.
Input : test_list = [2, 3, 5, 7, 8, 5, 3, 8], K = 8
Output : [7, 3]
Explanation : Elements before 8 are 7, 3.
Method #1: Using loop
In this, we iterate the list and look for each K, and extract the element preceding it.
Python3
# Python3 code to demonstrate working of
# Extract elements succeeded by K
# Using loop
# initializing list
test_list = [2, 3, 5, 7, 8, 5, 3, 5]
# printing original list
print("The original list is : " + str(test_list))
# initializing K
K = 5
# Using loop to extract elements succeeded by K
res = []
for idx in range(len(test_list) - 1):
# checking for succession
if test_list[idx + 1] == K:
res.append(test_list[idx])
# printing result
print("Extracted elements list : " + str(res))
OutputThe original list is : [2, 3, 5, 7, 8, 5, 3, 5]
Extracted elements list : [3, 8, 3]
Time Complexity: O(n)
Auxiliary Space: O(n)
Method #2: Using list comprehension
Another way to solve this question, in this, we use list comprehension as shorthand to solve the problem of getting elements.
Python3
# Python3 code to demonstrate working of
# Extract elements succeeded by K
# Using list comprehension
# initializing list
test_list = [2, 3, 5, 7, 8, 5, 3, 5]
# printing original list
print("The original list is : " + str(test_list))
# initializing K
K = 5
# List comprehension used as shorthand
res = [test_list[idx]
for idx in range(len(test_list) - 1) if test_list[idx + 1] == K]
# printing result
print("Extracted elements list : " + str(res))
OutputThe original list is : [2, 3, 5, 7, 8, 5, 3, 5]
Extracted elements list : [3, 8, 3]
Time Complexity: O(n) where n is the number of elements in the list “test_list”. list comprehension performs n number of operations.
Auxiliary Space: O(n), extra space is required where n is the number of elements in the list
Method 3: Using the enumerate() function.
Step-by-step approach:
- Initialize the original list and K value.
- Create an empty list to store the extracted elements.
- Loop through the list using the enumerate() function to access both the index and value of each element in the list.
- Check if the current element is not the last element of the list and if the next element is equal to K.
- If the condition is true, append the current element to the extracted elements list.
- After the loop, print the extracted elements list.
Python3
# Python3 code to demonstrate working of
# Extract elements succeeded by K
# Using enumerate()
# initializing list
test_list = [2, 3, 5, 7, 8, 5, 3, 5]
# printing original list
print("The original list is : " + str(test_list))
# initializing K
K = 5
# create an empty list to store extracted elements
res = []
# loop through the list using enumerate()
for idx, val in enumerate(test_list):
# check if the current element is not the last element of the list and if the next element is equal to K
if idx < len(test_list) - 1 and test_list[idx + 1] == K:
# append the current element to the extracted elements list
res.append(val)
# printing result
print("Extracted elements list : " + str(res))
OutputThe original list is : [2, 3, 5, 7, 8, 5, 3, 5]
Extracted elements list : [3, 8, 3]
Time complexity: O(n) as it involves looping through the list once.
Auxiliary space: O(k), where k is the number of elements succeeded by K in the given list.
Method #4: Using slicing and zip function
Step-by-step approach:
- Start by initializing the test_list and K as given in the problem statement.
- Create a new list called "res" to store extracted elements.
- Use slicing to create a new list called "next_list" that contains all elements in the original list except the first element.
- Use the zip function to create a tuple of each pair of elements in the original list and "next_list".
- Loop through each tuple and check if the second element in the tuple is equal to K.
- If it is, append the first element of the tuple to the "res" list.
- Finally, print the "res" list to display the extracted elements.
Python3
# initializing list
test_list = [2, 3, 5, 7, 8, 5, 3, 5]
# initializing K
K = 5
# create an empty list to store extracted elements
res = []
# use slicing to create a new list containing all elements except the first element
next_list = test_list[1:]
# use the zip function to create a tuple of each pair of elements in the original list and next_list
for x, y in zip(test_list, next_list):
# check if the second element in the tuple is equal to K
if y == K:
# append the first element in the tuple to the extracted elements list
res.append(x)
# print result
print("Extracted elements list : " + str(res))
OutputExtracted elements list : [3, 8, 3]
Time complexity: O(n), where n is the length of the list.
Auxiliary space: O(1), since we only use a few variables to store information about the list.
Similar Reads
Extract Elements from a Python List When working with lists in Python, we often need to extract specific elements. The easiest way to extract an element from a list is by using its index. Python uses zero-based indexing, meaning the first element is at index 0. Pythonx = [10, 20, 30, 40, 50] # Extracts the last element a = x[0] print(
2 min read
Python - Filter Tuples by Kth element from List Given a list of tuples, filter by Kth element presence in List. Input : test_list = [("GFg", 5, 9), ("is", 4, 3), ("best", 10, 29)], check_list = [4, 2, 3, 10], K = 2 Output : [('is', 4, 3)] Explanation : 3 is 2nd element and present in list, hence filtered tuple. Input : test_list = [("GFg", 5, 9),
5 min read
Python - Extract records if Kth elements not in List Given list of tuples, task is to extract all the tuples where Kth index elements are not present in argument list. Input : test_list = [(5, 3), (7, 4), (1, 3), (7, 8), (0, 6)], arg_list = [6, 8, 8], K = 1 Output : [(5, 3), (7, 4), (1, 3)] Explanation : All the elements which have either 6 or 8 at 1s
4 min read
Python - Rear element extraction from list of tuples records While working with tuples, we store different data as different tuple elements. Sometimes, there is a need to print specific information from the tuple like rear index. For instance, a piece of code would want just names to be printed on all the student data. Let's discuss certain ways in which one
8 min read
Python - Extract ith element of K key's value Given a dictionary, extract ith element of K key's value list. Input : test_dict = {'Gfg' : [6, 7, 3, 1], 'is' : [9, 1, 4], 'best' : [10, 7, 4]}, K = 'Gfg', i = 1 Output : 7 Explanation : 1st index of 'Gfg''s value is 7.Input : test_dict = {'Gfg' : [6, 7, 3, 1], 'is' : [9, 1, 4], 'best' : [10, 7, 4]
6 min read