The code:

print [c[i] for c in ['as','df'] for i in range(len(c))]

outputs: ['a','s','d','f']

while,

print [c[0] for c in ['as','df']]

outputs: ['a','d'] - The first letter of each word.

shouldn't the output be ['a','d','s','f'] - Why is this different?

It is the same difference as between

result = []
for c in ['as', 'df']:
    for i in range(len(c)):
        result.append(c[i])
print result

and

result = []
for c in ['as', 'df']:
    result.append(c[0])
print result

Which implies?
Can you please show me how the for ...in parses?

Edited 1 Year Ago by sarathsshanker

Well, here is the same loop with more prints to show what's happening

result = []
for c in ['as', 'df']:
    print 'c =', repr(c)
    for i in range(len(c)):
        print 'i =', repr(i)
        print 'c[%d] =' % i, repr(c[i])
        result.append(c[i])
print result

"""my output -->

c = 'as'
i = 0
c[0] = 'a'
i = 1
c[1] = 's'
c = 'df'
i = 0
c[0] = 'd'
i = 1
c[1] = 'f'
['a', 's', 'd', 'f']
"""

Edited 1 Year Ago by Gribouillis

This question has already been answered. Start a new discussion instead.