1

I am trying to search a list of strings and if it has a letter in a certain character position, I want to remove that string from the list. So far I have:

l = ['fast', 'attack', 'slow', 'baft', 'attack', 'baft']

for strings in l:
if 'a' in strings[0]:
    l.pop()

print(l)

Thanks.

  • When asking a question related to code, the very first tag you should be adding is the one for the language in which you're coding. Please [edit] your post to add that tag; you can remove the meaningless "loops", "char" and "string" to make space for it. – Ken White Jan 14 '22 at 02:23
  • `l.pop()` -> `l.remove(strings)` Caveat: [How to remove items from a list while iterating?](https://stackoverflow.com/q/1207406) – 001 Jan 14 '22 at 02:26
  • `[x for x in l if x[0]!='a']` – Chris Jan 14 '22 at 02:27
  • if you pop or remove iteratively you are running O(n^2) because each list element after the removal has to be moved one to the left. Creating an entirely new list and appending values is O(n) because appending to the end of a list is O(1). – Kaleba KB Keitshokile Jan 14 '22 at 04:15

2 Answers2

2

Well, first I would say that pop is not the best option for the procedure. pop will return the value, you are only looking to remove it. To remove an element from a list given its index you can do:

my_list = [1,2,3,4]
del(my_list[2])

Nevertheless, going through a for loop while removing the elements that are part of it is not a good idea. It would be best to create a new list with only the elements you want.

my_list = ['fast', 'attack', 'slow', 'baft', 'attack', 'baft']
my_new_list = []
for value_str in my_list:
    if 'a' != value_str[0]:
        my_new_list.append(value_str)

This can also be done more concisely using list comprehension. The snippet below does the same thing as the one above, but with less code.

my_list = ['fast', 'attack', 'slow', 'baft', 'attack', 'baft']
my_new_list = [value_str for value_str in my_list if value_str[0] != 'a']

Tim already gave you that snippet as an answer, but I felt that given the question it would be better to give you a more descriptive answer.

This is a good link to learn more about list comprehensions, if you are interested (they are pretty neat): Real Python - List Comprehensions

Arson 0
  • 757
  • 2
  • 14
0

Using a list comprehension we can try:

l = ['fast', 'attack', 'slow', 'baft', 'attack', 'baft']
output = [x for x in l if x[0] != 'a']
print(output)  # ['fast', 'slow', 'baft', 'baft']
Tim Biegeleisen
  • 502,043
  • 27
  • 286
  • 360