Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What does this statement really do?

Tags:

python

random

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)]
like image 254
user3078335 Avatar asked May 31 '26 09:05

user3078335


1 Answers

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)
like image 75
SethMMorton Avatar answered Jun 02 '26 22:06

SethMMorton



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!