Creating a List of ‘n’ Elements in Python

This article will explore various methods, which include simple multiplication, loop, and list comprehension, for creating a list of n-lists in Python. As an illustration, we will use list comprehension to generate a list of lists in one of the examples.


My intention is to generate a sequence of binary digits, consisting of only 0s and/or 1s, with a length of n. The desired outcome is that the sum of these values equals x.

For example:

import random
def foo(x,n):
    list = []
    test = 0
    while test == 0:
        for i in range(n):
            temp = int(random.random()+0.5)
        if sum(list) == x:
            test = 1
            print("here is your list ")
            return list
print(foo(5, 7))


here is your list [1, 0, 1, 0, 1, 1, 1]

Is there any way to optimize my function?


Here’s an uncomplicated method to accomplish it with the use of random.shuffle.

  1. I compile a tally of the desired quantity represented by [1].

  2. Next, I included the quantity of zeroes.

  3. Utilize the random.shuffle function to rearrange the list.

    import random
    def foo(x,n):
        list = []
    foo(5, 7)

The output obtained is [1, 0, 1, 1, 1, 0, 1], noting that it varies on each execution.

Frequently Asked Questions