IgnacioDLF
IgnacioDLF

Reputation: 40

How can I multiply a list inside a list with list comprehensions

So, let's say I have this structure:

list_test = [["A", "1", "Test"], ["B", "2", "Test2"], ["C", "3", "Test"]]

my desired output is:

[["A", "1", "Test"], ["A", "1", "Test"], ["A", "1", "Test"], ["B", "2", "Test2"], ["B", "2", "Test2"], ["B", "2", "Test2"], ["C", "3", "Test"], ["C", "3", "Test"], ["C", "3", "Test"]]

So I'm multiplying 3 times each list. I'm able to do it with extend and other ways of iteration with no issues, but I'm trying to learn solving it using list comprehensions.

I thought about something like this: [i * 4 for i in list_test] but that copies the list inside of itself, like this:

[['A', '1', 'Test', 'A', '1', 'Test', 'A', '1', 'Test'], ['B', '2', 'Test2', 'B', '2', 'Test2', 'B', '2', 'Test2'], ['C', '3', 'Test', 'C', '3', 'Test', 'C', '3', 'Test']]

[[i] * 4 for i in list_test] does something similar to what I want but it's inside another list, that's not what I want it.

Is it possible to solve this using comprehension?

Upvotes: 1

Views: 75

Answers (3)

CryptoFool
CryptoFool

Reputation: 23079

The way I'd do this is with a simple generator and a comprehension:

list_test = [["A", "1", "Test"], ["B", "2", "Test2"], ["C", "3", "Test"]]


def list_multiplier(list, n):
    for element in list:
        for i in range(n):
            yield element


list_result = [e for e in list_multiplier(list_test, 3)]
print(list_result)

Result:

[['A', '1', 'Test'], ['A', '1', 'Test'], ['A', '1', 'Test'], ['B', '2', 'Test2'], ['B', '2', 'Test2'], ['B', '2', 'Test2'], ['C', '3', 'Test'], ['C', '3', 'Test'], ['C', '3', 'Test']]

Upvotes: 1

Adam Smith
Adam Smith

Reputation: 54173

You could handle this by using two loops in your comprehension. Consider the trivial case:

given = [['a']]
want = [['a'], ['a'], ['a'], ['a']]

With this you could do:

got = [given[0] for _ in range(3)]

However your example is a little more complex, as you have multiple elements. You can instead do:

got = [sublst for sublst in given for _ in range(3)]

Upvotes: 3

SamudNeb
SamudNeb

Reputation: 221

[ entry for entry in list_test for _ in range(3) ]

should do the trick

Upvotes: 4

Related Questions