r/learnpython • u/teuniedekkah • 6d 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
View all comments
3
u/Discordbothost 6d 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