Trying to find all the commas in the list, what's wrong with that?

a = [',', 'hello',',', 'pear']

for i in a:
    d = 0
    c = []
    b = a[d]
    if b == ',':
        c.append(b)
        d += 1
    else:
        d += 1

print c

This seems to only return one comma if there are two in the code. How can i fix this?

+3
source share
3 answers

The problem is that you reset dare zero at the beginning of each iteration and clear c.

You need to move the initialization code outside the loop.

In doing so, you can simplify the whole cycle as follows:

a = [',', 'hello',',', 'pear']

c = []
for b in a:
    if b == ',':
        c.append(b)

print c

Now notice that such code expresses itself very well as an expression:

a = [',', 'hello',',', 'pear']

c = [b for b in a if b == ',']

print c
+5
source

You reassign an empty list to ceach iteration. You can change your logic as follows

c = []                # Initialized before the loop
for i in a:
    if i[0] == ',':
        c.append(b)

The best way to write this is to use list comprehension like

c = [item for item in a if item == ","]

This particular way of understanding lists is called list filtering.

+4
source
a = [',', 'hello',',', 'pear']
print len([x for x in a if x == ','])
+1
source

All Articles