-2

I am trying to get my code to go through each element in a list and decipher if it's the letter C. If it's a C remove it and print out the edited list.

Below is my code and it keeps looping.

letters = ["A", "B", "C", "D", "E", "C", "G"]
counter = 0
for letter in letters:
    while letter != "":
        if letter in letters == "C":
            letters.remove("C")
            counter += 1
print(letters)
jonrsharpe
  • 115,751
  • 26
  • 228
  • 437
Viksan
  • 1

1 Answers1

1

You can do something like this:

With the pop argument

letters = ["A", "B", "C", "D", "E", "C", "G"]
counter = 0
i=0
while i < len(letters): 
    if i<len(letters) and letters[i] == "C":
        letters.pop(i)
        counter += 1
    else:
        i+= 1

print(letters) #['A', 'B', 'D', 'E', 'G']

You can remove the counter and obtain the number of "C" in the list by doing: letters.count("C") at the begging

And you can use that to do:

With remove

letters = ["A", "B", "C", "D", "E", "C", "G"]
for _ in range(letters.count('C')):
    letters.remove('C')
print(letters) #['A', 'B', 'D', 'E', 'G']

You can also use a list comprehension like that:

With list comprehension

letters = ["A", "B", "C", "D", "E", "C", "G"]
letters = [l for l in letters if l != 'C']
print(letters) #['A', 'B', 'D', 'E', 'G']

Or, you could also use filter with a lambda function:

With filter

letters = ["A", "B", "C", "D", "E", "C", "G"]
letters = [*filter(lambda l: l!='C', letters)]
print(letters) #['A', 'B', 'D', 'E', 'G']
TKirishima
  • 742
  • 6
  • 18