Python – Remove characters till K element

Sometimes, while working with Python, we can have problem in which we need to get all elements in list occurring after particular character in list. This kind of problem can have application in data domains and web development. Lets discuss certain ways in which this task can be performed.

Method #1 : Using loop
This is brute force method in which this task can be performed. In this, we iterate the loop till we find K and then start appending characters, seeming like removing the elements before K.

filter_none

edit
close

play_arrow

link
brightness_4
code

# Python3 code to demonstrate 
# Remove characters till K element
# using loop
  
# Initializing list
test_list = ['gfg', 'is', 'best', 'for', 'geeks']
  
# printing original list
print("The original list is : " + str(test_list))
  
# Initializing K 
K = 'best'
  
# Remove characters till K element
# using loop
res = []
flag = 0
for ele in test_list:
    if ele == K:
        flag = 1 
        continue
    if flag:
        res.append(ele)
  
# printing result 
print ("List elements after removing all before K : " + str(res))

chevron_right


Output :



The original list is : ['gfg', 'is', 'best', 'for', 'geeks']
List elements after removing all before K : ['for', 'geeks']

 

Method #2 : Using index() + list comprehension
This is yet another way in which this task can be performed. In this, we first find the index of element and then use list comprehension + enumerate() to append only elements after that K.

filter_none

edit
close

play_arrow

link
brightness_4
code

# Python3 code to demonstrate 
# Remove characters till K element
# using list comprehension + enumerate() + index()
  
# Initializing list
test_list = ['gfg', 'is', 'best', 'for', 'geeks']
  
# printing original list
print("The original list is : " + str(test_list))
  
# Initializing K 
K = 'best'
  
# Remove characters till K element
# using list comprehension + enumerate() + index()
temp = test_list.index(K)
res = [ele for idx, ele in enumerate(test_list) if idx > temp]
  
# printing result 
print ("List elements after removing all before K : " + str(res))

chevron_right


Output :

The original list is : ['gfg', 'is', 'best', 'for', 'geeks']
List elements after removing all before K : ['for', 'geeks']



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.