Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Trying to find all the commas in the list, what is wrong with this?

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 only seems to return one comma when there are two within the code. How can I fix this?

like image 580
Jambofun Avatar asked Jan 18 '26 23:01

Jambofun


2 Answers

The problem is that you reset d to zero at the start of every iteration, and clear c.

You need to move the initialization code outside the loop.

While doing this, you could simplify the entire loop like so:

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

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

print c

Now observe that code like this lends itself very well to being expressed as a list comprehension:

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

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

print c
like image 78
NPE Avatar answered Jan 20 '26 11:01

NPE


You are reassigning an empty list to c every iteration. You can change your logic like this

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 this

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

This particular way of comprehending lists is called as filtering a list.

like image 39
thefourtheye Avatar answered Jan 20 '26 13:01

thefourtheye



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!