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?

Recommended Answers

All 4 Replies

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?

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']
"""
Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.