Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Generating a list of constants with a comprehension?

Tags:

python

list

I was wondering how I would generate a list of constants with a python comprehension?

For instance, if I wanted to generate a list of 100 number 5s, how would I do this?

I'm having trouble understanding this because the way I keep track of the number of elements in the list is distinct from what I would like to output.

like image 406
goldisfine Avatar asked Oct 20 '25 15:10

goldisfine


2 Answers

For immutable values, just multiply the list:

count = 100
[5] * count

For mutable values, use a list comprehension:

count = 100
[{'foo': 5} for _ in xrange(count)]

The _ name here is just a convention; it means we are ignoring the loop target name in the loop itself.

like image 199
Martijn Pieters Avatar answered Oct 22 '25 03:10

Martijn Pieters


You can do:

my_list = [5 for _ in xrange(100)]

You can also do:

import itertools
my_list = list(itertools.repeat(5, 100))
like image 34
Simeon Visser Avatar answered Oct 22 '25 04:10

Simeon Visser



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!