Sri991
Sri991

Reputation: 391

List comprehension for multiplying each string in a list by numbers from given range

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

Answers (3)

Jeevan Chaitanya
Jeevan Chaitanya

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

Roy2012
Roy2012

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

Ritika Gupta
Ritika Gupta

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

Related Questions