-2

Programming is all fine but I don't know the meaning of idx for idx. I know function enumerate(): for idx, c in enumerate but what is idx for idx meaning??

input

x = 'An apple a day, keeps the doctor away'
j = [idx for idx, c in enumerate(x,  start = 0) if c == 'a']
print(j)

output [3, 9, 12, 33, 35]

Leee Jeff
  • 27
  • 4
  • How would you write it as a `for` loop? Maybe comparing that with this comprehension will give you an answer – Mortz Nov 03 '22 at 08:55
  • `idx` is index when you use `enumerate` it iterates the value and the index of the value. – Ramesh Nov 03 '22 at 08:55

2 Answers2

0

In this example, idx iterates over the indices of the string x while c iterates over its values.

So when c == 'a', idx (which is the index of this 'a') will be added to the list.

Think it more like idx for (idx, c) in enumerate(x, start = 0) if c == 'a'

augustin64
  • 31
  • 1
  • 5
0

This is known as list comprehension, I would suggest looking up a few examples of list comprehension.

Here it is enumerating through the string, where idx is the index for each character, and c is the character itself. idx for idx, c in ... if c == 'a' is basically saying append idx to this new list if c == a. It is a one line way of writing the below:

j = []
for idx, c in enumerate(x,  start = 0):
    if c == 'a':
        j.append(idx)
Emi OB
  • 2,814
  • 3
  • 13
  • 29