repeat items in a list

Jussi Piitulainen jussi.piitulainen at helsinki.fi
Sun Mar 27 07:09:27 EDT 2016


Antonio Caminero Garcia writes:
> On Saturday, March 26, 2016 at 11:12:58 PM UTC+1, beli... at aol.com wrote:
>> I can create a list that has repeated elements of another list as
>> follows:
>> 
>> xx = ["a","b"]
>> nrep = 3
>> print xx
>> yy = []
>> for aa in xx:
>>     for i in range(nrep):
>>         yy.append(aa)
>> print yy
>> 
>> output:
>> ['a', 'b']
>> ['a', 'a', 'a', 'b', 'b', 'b']
>> 
>> Is there a one-liner to create a list with repeated elements?
>
> What about this?
>
> def rep_elements(sequence, nrep):
>     #return [ritem for item in sequence for ritem in [item]*nrep]
>     return list(chain.from_iterable(([item]*nrep for item in sequence)))
>
> sequence = ['h','o','l','a']
> print(rep_elements(sequence,  3))

A thing to know about the comprehension-syntaxes is that they correspond
precisely to nested loops (and conditions, but conditions don't appear
in the present example) with an .append inside.

xx = "ab"
nrep = 3
print([ aa for aa in xx for i in range(nrep) ])

(This has been posted in this thread a few times already, but I think
the systematic correspondence to the original loops was left unstated.
Apologies in advance if I missed something.)

The resulting list has some hidden name. The original loops should be
re-mentalized for an even closer correspondence as follows.

g47 = []
for aa in xx:            # Loopy ...
   for i in range(nrep): # ... do!
      g47.append(aa)     # <-- _This_ aa is one of the result items.
yy = g47

A thing about range objects is that they can be reused, so the present
example could also reuse just one.

xx = "ab"
reps = range(3)
print([ aa for aa in xx for i in reps ])



More information about the Python-list mailing list