-1

I am working on some Python homework and somehow the .remove() function does not work properly and I can't explain why.

Input:

['', '', 'Age,Gender,Weight (kg),Height (cm)', '28,Female,58,168', '33,Male,,188', '', '', '', '', '21, Male, 95, 198']

My code:

    for l in first:
        if str(l) == "":
            first.remove(l)
    print(first)

Output:

['Age,Gender,Weight (kg),Height (cm)', '28,Female,58,168', '33,Male,,188', '', '', '', '21, Male, 95, 198']

As you can see, the empty strings in the front get removed as intended but the ones later on don't. How do I properly clean the list by using "basic" Python syntax?

vvvvv
  • 25,404
  • 19
  • 49
  • 81
ijn
  • 21
  • 4
  • 1
    I think the `str(l)` is not necessary, but I don't see how that would affect anything. – ijn Oct 31 '20 at 17:19
  • 3
    never alter list while iterating over it. – buran Oct 31 '20 at 17:21
  • Your code will work if you change the `for` line to `for l in list(first):` because this iterates over a copy of `first` then the subsequent lines can remove items from `first` without modifying the thing being iterated over. – DisappointedByUnaccountableMod Oct 31 '20 at 17:25

2 Answers2

3

The best solution is by doing a list comprehension:

li = ['', '', 'Age,Gender,Weight (kg),Height (cm)', '28,Female,58,168', '33,Male,,188', '', '', '', '', '21, Male, 95, 198']
li = [s for s in li if s != ""]
print(li)  # ['Age,Gender,Weight (kg),Height (cm)', '28,Female,58,168', '33,Male,,188', '21, Male, 95, 198']

As @ShadowRanger noted, you can also more simply write it this way:

li = [s for s in li if s]

since "" evaluates to False.

vvvvv
  • 25,404
  • 19
  • 49
  • 81
  • Did you copy @Wasif Hasan? – new Q Open Wid Oct 31 '20 at 17:20
  • `if s` will do the trick without `!= ''`; the empty string is falsy, so non-empty strings will be kept. And this technically doesn't modify the original `list` (often not a problem, but worth nothing). – ShadowRanger Oct 31 '20 at 17:22
  • 1
    @zixuan: This is the standard answer for this *many* times duplicated question. People will naturally produce the same answer, because it's the simple, obvious answer. – ShadowRanger Oct 31 '20 at 17:23
2

You can use a list comprehension:

myList = ['', '', 'Age,Gender,Weight (kg),Height (cm)', '28,Female,58,168', '33,Male,,188', '', '', '', '', '21, Male, 95, 198']
myList = [x for x in myList if x != '']

You can use if x shorthand too as proposed by @shadowRanger:

myList = [x for x in myList if x]
ShadowRanger
  • 143,180
  • 12
  • 188
  • 271
Wasif
  • 14,755
  • 3
  • 14
  • 34
  • `if x` will do the trick without `!= ''`; the empty string is falsy, so non-empty strings will be kept. And this technically doesn't modify the original `list` (often not a problem, but worth nothing). – ShadowRanger Oct 31 '20 at 17:21