1

I have a list that I want to edit. For all the elements that start with '[x]', I want the list to remove those elements and place them into new list. But for the new list, in doing so, it should remove the '[x]' from the front of the elements.

list1 = ['[x]final', '[x]gym', 'midterm', '[x]class', 'school']

list1 becomes:

list1 = ['midterm', 'school']

new list that was created from removing the elements that had '[x]' in the front:

new_list = ['final', 'gym', 'class']

I am new to coding and am having difficulties with this.

  • Welcome to Stack Overflow. "I am new to coding and am having difficulties with this." - **what difficulties**? What do you imagine are the logical steps needed in order to solve the problem? What parts can and can't you write? For example, can you write code that tells you whether to include a specific string in the result? Can you write code to remove the `[x]` from a string that starts with it? Can you write code to do something with each element of a list? If you put those pieces together, why does it not solve the problem? – Karl Knechtel Nov 14 '22 at 18:52

1 Answers1

0

Since you are a beginner, the verbose way to do this is the following

list1 = ['[x]final', '[x]gym', 'midterm', '[x]class', 'school']

new_list = []
for s in list1:
    if s.startswith("[x]"):
        new_list.append(s[3:])

print(new_list)

However, you can take advantage of Python's list comprehension to do it in a single line, like this

list1 = ['[x]final', '[x]gym', 'midterm', '[x]class', 'school']

new_list = [s[3:] for s in list1 if s[0:3] == "[x]"]
print(new_list)

Both methods yield ['final', 'gym', 'class']

Alex P
  • 1,105
  • 6
  • 18