Open In App

Python | Get elements till particular element in list

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

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




# Python3 code to demonstrate working of
# Get elements till particular element in list
# using index() + list slicing
 
# initialize list
test_list = [1, 4, 6, 8, 9, 10, 7]
 
# printing original list
print("The original list is : " + str(test_list))
 
# declaring elements till which elements required
N = 8
 
# Get elements till particular element in list
# using index() + list slicing
temp = test_list.index(N)
res = test_list[:temp]
 
# printing result
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




# Python3 code to demonstrate working of
# Get elements till particular element in list
# using generator
 
# helper function to perform task
def print_ele(test_list, val):
    for ele in test_list:
        if ele == val:
            return
        yield ele
 
# initialize list
test_list = [1, 4, 6, 8, 9, 10, 7]
 
# printing original list
print("The original list is : " + str(test_list))
 
# declaring elements till which elements required
N = 8
 
# Get elements till particular element in list
# using generator
res = list(print_ele(test_list, N))
 
# printing result
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




# Python3 code to demonstrate working of
# Get elements till particular element in list
# using list.takewhile()
 
# initialize list
from itertools import takewhile
 
test_list = [1, 4, 6, 8, 9, 10, 7]
 
# printing original list
print("The original list is : " + str(test_list))
 
# declaring elements till which elements required
N = 8
 
# Get elements till particular element in list
# using list.takewhile()
res = list(takewhile(lambda x: x != N, test_list))
 
# printing result
print("Elements till N in list are : " + str(res))
#This code is contributed by Edula Vinay Kumar Reddy


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




#Python3 code to demonstrate working of
#Get elements till particular element in list
def get_elements_till(lst, n):
  if not lst:return []
  if lst[0] == n:return []
  return [lst[0]] + get_elements_till(lst[1:], n)
 
#initialize list
test_list = [1, 4, 6, 8, 9, 10, 7]
 
#printing original list
print("The original list is : " + str(test_list))
 
#declaring elements till which elements required
N = 8
 
#Get elements till particular element in list
res = get_elements_till(test_list, N)
 
#printing result
print("Elements till N in list are : " + str(res))
 
#This code is contributed by tvsk


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




# Python3 code to demonstrate working of
# Get elements till particular element in list
# using index() + list slicing and enumeration
 
# initialize list
test_list = [1, 4, 6, 8, 9, 10, 7]
 
# printing original list
print("The original list is : " + str(test_list))
 
# declaring element till which elements required
N = 8
 
# Get index of element N using enumeration
for i, x in enumerate(test_list):
    if x == N:
        index_N = i
        break
 
# Get elements till particular element in list
# using index() + list slicing
res = test_list[:index_N]
 
# printing result
print("Elements till N in list are : " + str(res))
# This code is contributed by vinay pinjala.


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)

  1. 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.
  2. Slicing the list using index_N takes O(index_N) time.
  3. 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]
# printing original list
print("The original list is : " + str(test_list))
N = 8
arr = np.array(test_list)
res = test_list[:np.where(arr == N)[0][0]]
# printing result
print("Elements till N in list are : " + str(res))
# This code is contributed by Jyothi pinjala.


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.



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

Similar Reads