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.
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.
You can do:
my_list = [5 for _ in xrange(100)]
You can also do:
import itertools
my_list = list(itertools.repeat(5, 100))
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With