Is there a way to append a variable amount of variables in a list in python? I want the number of variables in my list to be equal to y (y = 5)
Asked
Active
Viewed 1,512 times
-2
-
Lists don't hold variables. It sounds like you may be thinking about this the wrong way. Can you provide some context for what you're trying to do? – user2357112 May 24 '19 at 19:33
-
1What does "adding a variable amount of variables to a list" mean? Add an example of the behavior you want – rdas May 24 '19 at 19:33
-
You've said how *many* things you want in your list; you haven't said what you want them to be. – Scott Hunter May 24 '19 at 19:33
-
uh, yes? what will you be appending though? you may need to add some context here. – Paritosh Singh May 24 '19 at 19:33
-
I want to add 5 variables to the list and set them to a value afterwards. In my code I have a variable named y which is equal to 5. I want my list to have y variables, which is equal to 5. – Boran Apple May 24 '19 at 19:35
-
How do you expect to assign values to them later? – Scott Hunter May 24 '19 at 19:36
-
As an aside, it is a terminology/conceptual point, but you don't add *variables* to a list, you add *objects*. So you need to provide more context (in the question itself) about what, *exactly* you are trying to accomplish. – juanpa.arrivillaga May 24 '19 at 20:07
2 Answers
1
No, there is no way to do this. You cannot add variables to a list. You can only add objects to a list, and variables aren't objects in Python (like in most other languages, too).

Jörg W Mittag
- 363,080
- 75
- 446
- 653
-
-
Python is an object-oriented language. That means, everything you do, you do by manipulating objects. Variables aren't objects (just like in pretty much every other programming language), therefore, you can't manipulate them. (Other than bind them and de-reference them.) – Jörg W Mittag May 24 '19 at 19:38
-
While I think your answer is correct, what is an example of a language where "variables are objects"? Many common languages work the same as Python in this regard as far as I understand. – juanpa.arrivillaga May 24 '19 at 20:08
-
@juanpa.arrivillaga: Ioke and Seph, for example. Also, some Lisps, depending on how you look at it. – Jörg W Mittag May 24 '19 at 21:04
0
Reading your comments, I think you're trying to initialize the list with a certain number of items to then set those later? You don't actually need to do that in Python because lists are variable length, you can add more elements later, like:
my_list = []
my_list.append(20.0)
my_list.append("Hello world")
print(my_list)
>>> [20.0, "Hello world"]
It would help describing why you're trying to do what you describe. If for some reason you absolutely need to create the list with a fixed length to fill later, you can do it like this (in this example I initialize all items to None to make it clear that they are not meant to be the final values):
my_list = [None]*5
print(my_list)
>>> [None, None, None, None, None]

JohnO
- 777
- 6
- 10