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.
CodePudding user response:
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
CodePudding user response:
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']
CodePudding user response:
You can use str.startswith method to check if a string starts with a certain character (in this case 'a') and use list comprehension to create a new list of strings where none of the strings start with 'a' (since we don't want strings that start with 'a', we put in not)
out = [string for string in l if not string.startswith('a')]
Output:
['fast', 'slow', 'baft', 'baft']
