0

I am needing to create lists of random numbers (being either 0 or 1) with different lengths. I need lists with lengths of 10 numbers, 20 numbers, etc. all the way to 500. This is what I have:

import random
list1 = []
for x in range(10,501,10):
    list1.append(random.randint(0,1))
    print(list1)
    list1.clear()

So I'm getting 50 lists of only one random number. I understand that the range() is my problem because it is only an iterator, so what would I do to avoid writing 50 for loops to get all of these lists?

jpp
  • 159,742
  • 34
  • 281
  • 339

6 Answers6

4

The only way to generate 50 lists of random numbers (short of writing out all those commands sequentially) is to go through 50 loops generating the numbers. The standard way to do this in most programming languages is with nested loops. Some languages have features, or available libraries that can make this easier to write and/or more effecient. Python has a feature called list comprehensions that make creating lists very easy and convenient.

import random
[random.randint(0,1) for _ in range(10)]

They can also be nested to accomplish your task.

import random
[[random.randint(0,1) for _ in range(x)] for x in range(10,501,10)]

Timing:

from random import randint
from timeit import timeit

def lc():
    return [[randint(0,1) for _ in range(x)] for x in range(10,501,10)]

def forloop():
    outer = []
    for x in range(10,501,10):
        inner=[]
        for _ in range(x):
            inner.append(randint(0,1))
        outer.append(inner)
    return outer

print(timeit(lc,number=100))  # 9.2758308192958
print(timeit(forloop,number=100)) # 9.44730854274725

Hmmm. I was under the impression that list comps had more of a speed advantage over for loops.

Alan Hoover
  • 1,430
  • 2
  • 9
  • 13
  • Nope, I see nothing wrong with this answer, list comprehensions are fast, and upto a certain point beat numpy hands down in performance. Numpy just has too much overhead to be reasonably performant for small data. This just happens to be one unhappy scenario where `random.randint` is the bottleneck. Well, big deal, there are ways around that. – cs95 Apr 01 '18 at 06:40
2

A more efficient solution is to use numpy. See Why NumPy instead of Python lists?

import numpy as np

res = [np.random.randint(0, 2, x) for x in range(10, 501, 10)]

This creates a list of arrays of binary values, with arrays of length 10, 20, ... , 490, 500.

Any answer which claims nested list comprehensions are efficient for this task should note that they are ~100x slower versus numpy in this instance.

Benchmarking

import numpy as np
import random

def method_np():
    return [np.random.randint(0, 2, x) for x in range(10, 501, 10)]

def method_lst():
    return [[random.randint(0,1) for _ in range(x)] for x in range(10,501,10)]

%timeit method_np()    # 359 µs
%timeit method_lst()   # 37.3 ms
jpp
  • 159,742
  • 34
  • 281
  • 339
  • 1
    Why would you introduce numpy here? As far as we're aware, speed isn't even a concern. – Daniel Mar 31 '18 at 21:57
  • 1
    Let's flip the question around. Why would you use nested loops to add items to lists one by one when you can use a purpose-built library to vectorise this? – jpp Mar 31 '18 at 21:59
  • 5
    Maybe because numpy is not part of the Python standard library, and the potential hassle to install it and get started with it are simply not worth it for a relatively trivial problem like this one. – Daniel Mar 31 '18 at 22:04
  • 3
    I would counter to say, *as soon as* you want / need to perform numerical Python work, you should install `numpy`. – jpp Mar 31 '18 at 22:10
0

You need nested loops:

import random
list1 = []
for x in range(10,501,10):
    for e in range(x):
        list1.append(random.randint(0,1))
    print(list1)
    list1.clear()
whackamadoodle3000
  • 6,684
  • 4
  • 27
  • 44
0

I guess this solves your problem:

   import random
        lists = []
        for x in range(10,501,10):
            l = []
            for _ in range(x):
                l.append(random.randint(0,1))
            lists.append(l)
    print(lists)
czr
  • 658
  • 3
  • 13
0

Issues : There are 2 issues with your code first one is range() and second one is indent of print(list1) list1.clear() .

Fixed Code :

import random
list1 = []
ranges = [10,501,10]
for y in ranges:
    for x in range(0,y):
        list1.append(random.randint(0,1))
    print(list1)
    list1.clear()
toheedNiaz
  • 1,435
  • 1
  • 10
  • 14
0

Since it seems you simply need the list printed out, you can use a list comprehension to generate the list of a certain length.

import random
max_list_len = 500
for l in range(1, max_list_len + 1):
    print([random.randint(0, 1) for i in range(0, l)])
tech2077
  • 1
  • 1