Reputation: 781
I am new to python. Found a code online I am trying to understand. Can someone please help me understand what the following statement actually does?
self.record = [random.choice([0.0, 1.0]) for _ in range(10)]
Upvotes: 2
Views: 124
Reputation: 48725
random.choice([0.0, 1.0])
The random.choice
method will randomly pick an element of a given sequence. Here, it will randomly pick 0.0
, or 1.0
.
range(10)
This function will create a 10 element list (or iterable on python3)
[function() for _ in range(10)]
This is a list comprehension that will call a function 10 times, and place the results in a list. The _
is a python convention meaning "I need a variable here, but I won't use it's value"
[random.choice([0.0, 1.0]) for _ in range(10)]
This creates a list 10 elements long, where each element is either 0.0
or 1.0
, randomly chosen.
self.record = [random.choice([0.0, 1.0]) for _ in range(10)]
This places the 10 element list into the instance variable record
inside your current class.
It is equivalent to the following code
self.record = []
for _ in range(10):
num = random.choice([0.0, 1.0])
self.record.append(num)
Upvotes: 10
Reputation: 61498
It means what it says:
self.record = [ random.
#self.record shall be a name for: a list consisting of one random
choice( [0.0, 1.0]) for _
#choice taken from the list [0.0, 1.0], for each value (which we don't care about)
in range( 10)]
#in a range from 0 up to but not including 10.
Upvotes: 1