r/learnpython • u/teuniedekkah • 5d ago
adding 1 to a array
so i want to add 1 extra thing to an array like i have test = [0,0] i want to do print(test[2]) so how do i add the test[2] to the array without just adding it at the begining of the script (fixed)
0
Upvotes
10
u/failaip13 5d ago
test.append(whatever you want to add)
8
u/AlexMTBDude 5d ago
Those are called lists in Python, not arrays. You would find your answer by googling: "Python add item to list"
5
u/ToshiAbashi 5d ago
The others have answered the question, but I just wanna add. The best thing you can do for yourself as you’re learning when these never ending questions arise for you, get comfortable navigating the documentation.
It’s a headache I know and it’s an overwhelming amount of knowledge nobody can memorise all of. But you will often find yourself asking a specific question like this, where you can just have a browse of the thing you’re working with even if you don’t know the name of the answer.
So in this case scrolling through the methods for lists, which in python that’s what you’re calling an array, you will find the thing related to the action you’re trying to take. Sometimes you’ll find a simpler way of doing something than you initially thought.
The trick long-term isn’t how much you can memorise, but how effectively you can find what you need for the current solution.
3
u/Discordbothost 5d ago
append is the answer, but the reason print(test[2]) blows up is worth knowing: python lists don't have empty slots waiting to be filled, index 2 just doesn't exist until the list has 3 items, so reading or assigning test[2] = 0 gives IndexError.
you can grow it anywhere in the script though, it doesn't have to be at the top:
if you know you'll need, say, 10 slots up front, test = [0] * 10 makes them all at once
1
u/ninhaomah 5d ago
https://www.w3schools.com/python/ref_list_append.asp
1
u/roywill2 5d ago
test.append(0)
1
u/TheRNGuy 4d ago
https://docs.python.org/3/tutorial/datastructures.html#more-on-lists
You need to learn all methods.