user4966454
user4966454

Reputation:

incrementing and iterating inside list comprehension

x = ['a','b','c','y','h']
e = 'fork'
w = 'knife'
s = 'what %s is the %s  doing inside the %s'
t = [s%(x[0],e,w) for i in x]
print t

If I run the above code I get something like :

'what a is the for doing inside the knife' repeated the amount of times there are elements in x. What I want to do instead is iterate over x so that the output is something like :

'what a is the fork doing inside the knife','what b is the fork doing inside the knife'
'what c is the fork doing inside the knife','what y is the fork doing inside the knife',
'what h is the fork doing inside the knife'

How do I do this in an list comprehension? is it better to do this in a loop instead?

Upvotes: 0

Views: 99

Answers (1)

hilberts_drinking_problem
hilberts_drinking_problem

Reputation: 11602

Replace t = [s%(x[0],e,w) for i in x] with t = [s%(i,e,w) for i in x]; you are not iterating over x.

Upvotes: 3

Related Questions