SivaR
SivaR

Reputation: 19

Create multiple objects inside forloop

Python noob here.

I want to create a bunch of list using a forloop.

They all need to in the form of l1, l2, l3, l4, etc.

I am trying to use the following code and I keep getting error, "SyntaxError: can't assign to function call"

The following is the code and any help will be appreciated.

rets = [1,2,3,4,5,6,7,8,9,10]

for i in range(0, len(rets)-1):
  object("L", str(i)) = [0]*(len(rets)-i)

So the objects need to be list that repeats 0. And the length should decrease by i. For eg, the last object will have length of 1.

I believe the error is related to the name of list but I am unable to fix it.

Upvotes: 0

Views: 453

Answers (2)

Son Nguyen
Son Nguyen

Reputation: 1767

What you are trying to achieve is creating variable names (L1, L2, etc.), which can’t be done by creating an object like you did, and I’m not aware of any ways to dynamically creating variable names like this outside of PHP 😂.

You can instead store all the variables insides a list, for example. Then you can pull those values out using a simple for loop.

rets = [1,2,3,4,5,6,7,8,9,10]
values = []

for i in range(0, len(rets)-1):
  values.append([0]*(len(rets)-i))

for value in values:
  # Do something with value

You can use list comprehension for a cleaner syntax:

rets = [1,2,3,4,5,6,7,8,9,10]
values = [[0]*(len(rets)-i) for i in range(1, len(rets)-1)]

Upvotes: 1

Ata Reenes
Ata Reenes

Reputation: 188

Since i didn't get the question properly i will try to help as much as i can so if you want to achieve list of zeros with range you can use following code

rets = [1,2,3,4,5,6,7,8,9,10]
list_of_lists = []

for item in rets:
    list_of_lists.append([0]*item)

it will give you the following output;

[[0], [0, 0], [0, 0, 0], [0, 0, 0, 0], [0, 0, 0, 0, 0], [0, 0, 0, 0, 0, 0], [0, 0, 0, 0, 0, 0, 0], [0, 0, 0, 0, 0, 0, 0, 0], [0, 0, 0, 0, 0, 0, 0, 0, 0], [0, 0, 0, 0, 0, 0, 0, 0, 0, 0]]

if you want to achieve something like ["L1,L2"] you can use the following snippet code;

for times in rets :
    added_list_here = []
    for i in range(times) :
        added_list_here.append(f'L{i}')
    
    list_of_lists.append(added_list_here)

and it will give you the following output;

[['L0'], ['L0', 'L1'], ['L0', 'L1', 'L2'], ['L0', 'L1', 'L2', 'L3'], ['L0', 'L1', 'L2', 'L3', 'L4'], ['L0', 'L1', 'L2', 'L3', 'L4', 'L5'], ['L0', 'L1', 'L2', 'L3', 'L4', 'L5', 'L6'], ['L0', 'L1', 'L2', 'L3', 'L4', 'L5', 'L6', 'L7'], ['L0', 'L1', 'L2', 'L3', 'L4', 'L5', 'L6', 'L7', 'L8'], ['L0', 'L1', 'L2', 'L3', 'L4', 'L5', 'L6', 'L7', 'L8', 'L9']]

Upvotes: 1

Related Questions