nobody
nobody

Reputation: 835

python: convenient way to create list of strings of repeated elements

How can I create a list like this:

["a","a","a",... (repeating "a" a hundred times") "b","b","b",(repeating "b" a hundred times.. )]

If I write ["a","b"] * 100, then I get ["a","b","a","b",...], which is not exactly what I want.

Is there any function as simple as this one but gives me the result I want?

Upvotes: -1

Views: 900

Answers (4)

LetzerWille
LetzerWille

Reputation: 5658

from itertools import repeat

list(repeat('a',100)) +  list(repeat('b',100))

Upvotes: 0

Saket Mittal
Saket Mittal

Reputation: 3876

sak = ['a','b','c','d']
list = sak*100
print sorted(list)

var = ['a','b']
list = sorted(var*100)

Upvotes: 1

Eugene Soldatov
Eugene Soldatov

Reputation: 10135

Just sum two lists produced by multiplication first and second elements:

['a']*100 + ['b']*100

It's faster than list comprehension and sort:

python -m timeit "sorted(['a', 'b']*100)"
100000 loops, best of 3: 9.76 usec per loop

python -m timeit "[x for x in ['a', 'b'] for y in range(100)]"
100000 loops, best of 3: 5.15 usec per loop

python -m timeit "['a']*100 + ['b']*100"
1000000 loops, best of 3: 1.86 usec per loop

Upvotes: 5

Ignacio Vazquez-Abrams
Ignacio Vazquez-Abrams

Reputation: 798536

No.

>>> [x for x in ['a', 'b'] for y in range(100)]
['a', 'a', 'a', 'a', 'a', ..., 'b', 'b', 'b', 'b', 'b', ...]

Upvotes: 3

Related Questions