Reputation: 391
I am trying out the list comprehensions. But I got stuck when I tried to write a list comprehension for the following code.
a = ['x','y','z']
result = []
for i in a:
for j in range(1,5):
s = ''
for k in range(j):
s = s + i
result.append(s)
result
output for this is:
['x', 'xx', 'xxx', 'xxxx', 'y', 'yy', 'yyy', 'yyyy', 'z', 'zz', 'zzz', 'zzzz']
Is it even possible to write a list comprehension for this code? if it is how would you write it?
Upvotes: 5
Views: 364
Reputation: 1384
Possible!!!!
>>> a = ['x','y','z']
>>> sorted([i*j for j in range(1,5) for i in a])
['x', 'xx', 'xxx', 'xxxx', 'y', 'yy', 'yyy', 'yyyy', 'z', 'zz', 'zzz', 'zzzz']
Upvotes: 1
Reputation: 12503
Here it is:
[ x * i for x in ['x','y','z'] for i in range(1,5) ]
The result:
['x', 'xx', 'xxx', 'xxxx', 'y', 'yy', 'yyy', 'yyyy', 'z', 'zz', 'zzz', 'zzzz']
Upvotes: 12
Reputation: 573
a = ['x','y','z']
result = []
result+=[i*j for i in a for j in range(1,5)]
result
This will work
Upvotes: 2