Python | Get elements till particular element in list

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.

filter_none

edit
close

play_arrow

link
brightness_4
code

# 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))

chevron_right


Output :



The original list is : [1, 4, 6, 8, 9, 10, 7]
Elements till N in list are : [1, 4, 6]

 

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.

filter_none

edit
close

play_arrow

link
brightness_4
code

# 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))

chevron_right


Output :

The original list is : [1, 4, 6, 8, 9, 10, 7]
Elements till N in list are : [1, 4, 6]


My Personal Notes arrow_drop_up

Check out this Author's contributed articles.

If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.

Please Improve this article if you find anything incorrect by clicking on the "Improve Article" button below.




Article Tags :

Be the First to upvote.


Please write to us at contribute@geeksforgeeks.org to report any issue with the above content.