Python | Get elements till particular element in list
Last Updated :
06 Apr, 2023
Sometimes, while working with Python list, we can have a requirement in which we need to remove all the elements after a particular element, or, get all elements before a particular element. These both are similar problems and having a solution to it is always helpful. Let’s discuss certain ways in which this task can be performed.
Method #1 : Using index() + list slicing This problem can be solved using the combination of these functions. The index() can be used to find the index of desired element and list slicing can perform the remaining task of getting the elements.
Python3
test_list = [ 1 , 4 , 6 , 8 , 9 , 10 , 7 ]
print ("The original list is : " + str (test_list))
N = 8
temp = test_list.index(N)
res = test_list[:temp]
print ("Elements till N in list are : " + str (res))
|
Output :
The original list is : [1, 4, 6, 8, 9, 10, 7]
Elements till N in list are : [1, 4, 6]
The time complexity of the given code is O(n), where n is the length of the input list.
The auxiliary space complexity of the code is O(n), as a new list is created with the elements up to the index of N using list slicing.
Method #2 : Using generator This task can also be performed using the generator function which uses yield to get the elements just till the required element and breaks the yields after that element.
Python3
def print_ele(test_list, val):
for ele in test_list:
if ele = = val:
return
yield ele
test_list = [ 1 , 4 , 6 , 8 , 9 , 10 , 7 ]
print ("The original list is : " + str (test_list))
N = 8
res = list (print_ele(test_list, N))
print ("Elements till N in list are : " + str (res))
|
Output :
The original list is : [1, 4, 6, 8, 9, 10, 7]
Elements till N in list are : [1, 4, 6]
Time Complexity: O(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 list.takewhile()
This method can be used to get the elements till a certain element in the list, it takes a function as an argument and stop taking elements when that function returns false.
Python3
from itertools import takewhile
test_list = [ 1 , 4 , 6 , 8 , 9 , 10 , 7 ]
print ( "The original list is : " + str (test_list))
N = 8
res = list (takewhile( lambda x: x ! = N, test_list))
print ( "Elements till N in list are : " + str (res))
|
Output
The original list is : [1, 4, 6, 8, 9, 10, 7]
Elements till N in list are : [1, 4, 6]
Time complexity: O(n)
Auxiliary Space: O(n)
Method#4: Using Recursive method.
- Define a function named get_elements_till which takes a list lst and an integer n as arguments.
- Check if the list is empty. If it is, return an empty list.
- Check if the first element of the list is equal to n. If it is, return an empty list.
- If the above conditions are not satisfied, return a list containing the first element of the list followed by the result of calling the function recursively on the remaining elements of the list.
- Initialize the input list and the integer N.
- Call the get_elements_till function with the input list and integer N as arguments.
- Print the result.
Python3
def get_elements_till(lst, n):
if not lst: return []
if lst[ 0 ] = = n: return []
return [lst[ 0 ]] + get_elements_till(lst[ 1 :], n)
test_list = [ 1 , 4 , 6 , 8 , 9 , 10 , 7 ]
print ( "The original list is : " + str (test_list))
N = 8
res = get_elements_till(test_list, N)
print ( "Elements till N in list are : " + str (res))
|
Output
The original list is : [1, 4, 6, 8, 9, 10, 7]
Elements till N in list are : [1, 4, 6]
Time complexity: O(n), where n is the length of the input list.
Auxiliary Space: O(n), where n is the length of the input list, due to the recursive calls made to the function.
Method#5: Using enumeration
Here’s the step-by-step algorithm for getting elements till a particular element in a list using index() and list slicing with enumeration:
- Initialize the original list test_list.
- Declare the particular element N till which the elements are required.
- Loop over the elements in test_list along with their index using enumerate().
- In each iteration, check if the current element is equal to N.
- If the current element is equal to N, save its index in a variable index_N and break out of the loop.
- Use index_N to slice the list and get the elements before N.
- Print the original list and the elements before N.
Python3
test_list = [ 1 , 4 , 6 , 8 , 9 , 10 , 7 ]
print ( "The original list is : " + str (test_list))
N = 8
for i, x in enumerate (test_list):
if x = = N:
index_N = i
break
res = test_list[:index_N]
print ( "Elements till N in list are : " + str (res))
|
Output
The original list is : [1, 4, 6, 8, 9, 10, 7]
Elements till N in list are : [1, 4, 6]
Time complexity: O(n)
- Finding the index of the first occurrence of N in test_list takes O(n) time in the worst case, where n is the length of test_list.
- Slicing the list using index_N takes O(index_N) time.
- Therefore, the time complexity of the algorithm is O(n) in the worst case.
Auxiliary Space: O(1)
The algorithm uses a constant amount of extra space, so the space complexity is O(1).
Method#6: Using numpy.where():
Algorithm:
1.Convert the list to a numpy array
2.Find the index of the element N using np.where() function
3.Slice the list from the beginning to the index of N
Python3
import numpy as np
test_list = [ 1 , 4 , 6 , 8 , 9 , 10 , 7 ]
print ( "The original list is : " + str (test_list))
N = 8
arr = np.array(test_list)
res = test_list[:np.where(arr = = N)[ 0 ][ 0 ]]
print ( "Elements till N in list are : " + str (res))
|
Output:
The original list is : [1, 4, 6, 8, 9, 10, 7]
Elements till N in list are : [1, 4, 6]
Time complexity: O(n)
Converting the list to a numpy array takes O(n) time
Finding the index of N using np.where() takes O(1) time on average
Slicing the list takes O(n) time in the worst case (when N is the last element of the list)
Space complexity: O(n)
Converting the list to a numpy array requires creating a new array with the same elements, thus taking O(n) space.
Similar Reads
Python - Nearest occurrence between two elements in a List
Given a list and two elements, x and y find the nearest occurrence index of element x from element y. Input : test_list = [2, 4, 5, 7, 8, 6, 3, 8, 7, 2, 0, 9, 4, 9, 4], x = 4, y = 6 Output : 1 Explanation : 4 is found at 1, 12 and 14th index, 6 is at 5th index, nearest is 1st index.Input : test_list
5 min read
Python - Extracting Priority Elements in Tuple List
Sometimes, while working with Python Records, we can have a problem in which we need to perform extraction of all the priority elements from records, which usually occur as one of the binary element tuple. This kind of problem can have possible application in web development and gaming domains. Let'
5 min read
Python - Alternate Minimum element in list
Some of the list operations are quite general and having shorthands without needing to formulate a multiline code is always required. Wanting to construct the list consisting of all the alternate elements of the original list is a problem that one developer faces in day-day applications and sometime
4 min read
Python | Get Kth element till N
Sometimes, we may come across a utility in which we require to get the first N sublist elements that too only a particular index. This can have an application in queuing to get only the Kth N personâs name. Letâs discuss certain ways in which this can be done. Method #1 : Using list comprehension an
3 min read
How to Get the Number of Elements in a Python List?
In Python, lists are one of the most commonly used data structures to store an ordered collection of items. In this article, we'll learn how to find the number of elements in a given list with different methods. Example Input: [1, 2, 3.5, geeks, for, geeks, -11]Output: 7 Let's explore various ways t
3 min read
Python - Adjacent elements in List
Given a List extract both next and previous element for each element. Input : test_list = [3, 7, 9, 3] Output : [(None, 7), (3, 9), (7, 3), (9, None)] Explanation : for 7 left element is 3 and right, 9. Input : test_list = [3, 7, 3] Output : [(None, 7), (3, 3), (7, None)] Explanation : for 7 left el
3 min read
Python | Split list into lists by particular value
The goal here is to split a list into sublists based on a specific value in Python. For example, given a list [1, 4, 5, 6, 4, 7, 4, 8] and a chosen value 4, we want to split the list into segments that do not contain the value 4, such as [[1], [5, 6], [7], [8]]. Letâs explore different approaches to
4 min read
Python - Check if previous element is smaller in List
Sometimes, while working with Python lists, we can have a problem in which we need to check for each element if its preceding element is smaller. This type of problem can have its use in data preprocessing domains. Let's discuss certain problems in which this task can be performed. Input : test_list
5 min read
Python - List Elements with given digit
Given list of elements and a digit K, extract all the numbers which contain K digit. Input : test_list = [56, 72, 875, 9, 173], K = 5 Output : [56, 875] Explanation : 56 and 875 has "5" as digit, hence extracted. Input : test_list = [56, 72, 875, 9, 173], K = 4 Output : [] Explanation : No number ha
6 min read
Python | Minimum element in tuple list
Sometimes, while working with data in form of records, we can have a problem in which we need to find the minimum element of all the records received. This is a very common application that can occur in Data Science domain. Let's discuss certain ways in which this task can be performed. Method #1 :
5 min read