0

I want to find position of all instances of a letter(w) in a list, here is what I do:

a=list('Hello, welcome to my world.')
b=[]
for i in a:
    if i=='w':
        b.append(a.index(i))
        
print(b)     


    

but it just returns this : [7, 7]

can somebody tell me why python behaves like this ?

1 Answers1

0

You can use enumerate which returns a counter for every object starting from 0.

b=[y for y,x in enumerate(a) if x=="w"]       

Output:

[7, 21]
  • Can you please explain why using "for" doesn't help here? what it is doing exactly that reaches this result "[7, 7]" ? I want to know it's behavior – Mehrdad Jun 27 '21 at 07:12
  • @Mehrdad, this is a list comprehension. ```enumerate``` adds a counter or a number. Example ```list1=['a','b','c']```. Take this list. Now when you add ```for x,y in enumerate(list1)```. It returns ```1 'a'``` , ```2 'b'``` and so on –  Jun 27 '21 at 07:15