Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 975
Sri991 Avatar asked May 23 '20 06:05

Sri991


People also ask

How do you multiply a string list in Python?

This has probably been asked before, please read the language's docs at docs.python.org and consider using a simple "for i in range" loop where you can c += [a[i]] * b[i] in each iteration. A better duplicate target: Repeat each item in a list a number of times specified in another list.

Can you do list comprehension with strings?

List comprehension works with string lists also. The following creates a new list of strings that contains 'a'. Above, the expression if 'a' in s returns True if an element contains a character 'a'.

How do you multiply a range of numbers in Python?

Use a list comprehension to multiply each number in a range by specific number, e.g. result = [num * 2 for num in range(1, 6)] . The list comprehension iterates over the range and uses the multiplication * operator to multiply the current number by another number.


3 Answers

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']
like image 118
Roy2012 Avatar answered Nov 15 '22 02:11

Roy2012


a = ['x','y','z']
result = []
result+=[i*j for i in a for j in range(1,5)]
result

This will work

like image 31
Ritika Gupta Avatar answered Nov 15 '22 04:11

Ritika Gupta


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']
like image 43
Jeevan Chaitanya Avatar answered Nov 15 '22 04:11

Jeevan Chaitanya