marillion
marillion

Reputation: 11170

How to assign a list with a variable to a variable in Python

I have a list where one of the elements is a variable and it can take a value between 60 to 120.

[0, 1, 2, 3, 4, v]

if I want to print this list for v ranges from 60 to 120:

for v in range(60,121):
    print([0, 1, 2, 3, 4, v])

gives the expected result. However if I assign this list to a variable such as:

l = [0, 1, 2, 3, 4, v]

I get an error, because v is undefined. If I try assigning an initial value to v, then declare the list, I do not get an error anymore, but I get stuck with a list where v has already assigned a value:

v = 60
l = [0, 1, 2, 3, 4, v]    
for v in range(60,121):
    print(l)

always yields [0, 1, 2, 3, 4, 60].

The reason I am trying to assign this list to a variable is, I use this list in many locations in a way longer script, and I need to do a for loop for certain calculations using this list for the range 60 to 120 for v. One solution is typing the list every time it needs to be used, but that requires me to replace all occurrences of this list in the script if I need to change any other list element.

I think my question is: is there a way to assign a list that contains a variable (v) as an element to a variable (l) to be used throughout your script?

Is there a good programmatical way to handle something like this?

Upvotes: 3

Views: 2387

Answers (5)

feverdreme
feverdreme

Reputation: 527

Well it really depends on exactly how you're going to use this. If you want to evaluate something that uses this list at every possible value then

for v in range(60,121):
  l = [0,1,2,3,4,v]
  # code here

If you want to just assign a list with a certain value, just do something like this

def l(v):
  return [0,1,2,3,4,v]

Upvotes: 1

tdelaney
tdelaney

Reputation: 77337

Here is another solution... but I think its a bad one for anything but a small script. You could put a sentinel value in place of the anticipated v. The problem is that if multiple bits of code use the list at the same time, one will overwrite the other's value, corrupting all. I'm including it because it most closely matches your original experiments.

oft_used_list = [0, 1, 2, 3, 4, None]    
for v in range(60,121):
    oft_used_list[-1] = v
    print(oft_used_list)

Upvotes: 0

PDHide
PDHide

Reputation: 19929

print([1,2,3,4,*range(60,70)])

if you want to store as variable then

v= [*range(60,70)]
print([1,2,3,4,v])

if you don't want nested list then:

c=[1,2,3,4]



[c.append(i) for i in v ]
print(c)

Or

print([1,2,3,4,[i for i in v ]]) 

Upvotes: 1

costaparas
costaparas

Reputation: 5237

You could define the list like this:

l = [0, 1, 2, 3, 4]

And introduce v whenever you use it:

for v in range(60, 121):
    print(l + [v])

Upvotes: 1

Barmar
Barmar

Reputation: 780724

Define a function.

def mylist(x):
    return [0, 1, 2, 3, 4, x]

for v in range(60, 121):
    print(mylist(v))

Upvotes: 2

Related Questions