Sergei
Sergei

Reputation: 605

List append in loop question

How can i modify this code to make 3 lists with 5 elements in each instead of as it is now; 3 lists with 5/10/15 elements?

import random

y = []

def autoSolve():
    for i in range(5):
        z = random.randrange(1, 10)
        y.append(z)
    print(y, end="")

for i in range(3):
    print("number", i + 1,)
    autoSolve()
    print()

Upvotes: 6

Views: 30419

Answers (6)

Subham
Subham

Reputation: 411

import random

def autoSolve():
    y = []
    for i in range(5):
        z = random.randrange(1, 10)
        y.append(z)
    return y #you could return instead, it'd be cleaner 
   
for i in range(3):
    print("number", i + 1,)
    print(autoSolve())
number 1
[4, 8, 4, 2, 9]
number 2
[8, 2, 4, 8, 9]
number 3
[4, 8, 1, 3, 5]

[Program finished]

Alternate way using list comprehension,

import random

lists = [[random.randrange(1, 10) for i in range(5)] for j in range(3)]

for lst in lists:
  print(f"Number: {lists.index(lst)+1}")
  print(f"List: {lst}")
  print("") 

Using random.choices

import random

lists = [random.choices(range(10), k = 5)for j in range (3 )]
    

for i, lst in enumerate(lists, start=1):
  print(f"Number: {i}")
  print(f"List: {lst}")
  print("") 

Number: 1
List: [0, 8, 4, 5, 0]

Number: 2
List: [3, 4, 6, 2, 1]

Number: 3
List: [9, 6, 5, 9, 9]


[Program finished]

Upvotes: 0

Raihan
Raihan

Reputation: 171

i think this would be suitable solution for this problem.

import random

y = []

def autoSolve():
    x = []
    for i in range(5):
        z = random.randrange(1, 10)
        x.append(z)
    y.append(x)
    print(y, end="")

 for i in range(3):
    print("number", i + 1,)
    autoSolve()
    print()

here output will generate as this [ [ ], [ ], [ ] ] formate A list with 3 inner list of 5 element

Upvotes: -1

Fábio Diniz
Fábio Diniz

Reputation: 10353

import random

y = []

def autoSolve():
    x = []
    for i in range(5):
        z = random.randrange(1, 10)
        x.append(z)
    print(x, end="")
    return x

for i in range(3):
    print("number", i + 1,)
    y.append(autoSolve())
    print()

Upvotes: 0

Sanjay Manohar
Sanjay Manohar

Reputation: 7026

You are printing the same list y each time.

y starts off empty.

The first iteration of your for loop, y ends up with 5 elements.

The second iteration, y.append causes it to increase to 10 elements.

To prevent this, put the line

y=[]

inside the autoSolve() method.

Upvotes: 1

Amber
Amber

Reputation: 526563

Move the y = [] to the beginning of autoSolve.

Upvotes: 0

Dogbert
Dogbert

Reputation: 222088

Move y = [] into the autoSolve method, so that it's reset on every call.

def autoSolve():
    y = []
    for i in range(5):
        z = random.randrange(1, 10)
        y.append(z)
    print(y, end="")

Upvotes: 10

Related Questions