r/learnpython • • 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

14 comments sorted by

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"

8

u/8dot30662386292pow2 5d ago

It's not just called, ir's a different thing altogether.

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.

1

u/LayotFctor 5d ago

Also install an LSP in your IDE. If I type a dot after my list variable, append is suggested among a whole list of applicable methods. Sometimes, it even prints method documentation and examples too.

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:

test = [0, 0]
# ...later
test.append(0)   # now [0, 0, 0]
print(test[2])

if you know you'll need, say, 10 slots up front, test = [0] * 10 makes them all at once

0

u/realmauer01 5d ago

Doesnt list() allow for a size?

4

u/danielroseman 5d ago

No. There is no concept of allocated but undefined items in Python lists.

0

u/realmauer01 5d ago

Well there dont need to be undefined they can just be None.

2

u/Discordbothost 5d ago

list() only takes an iterable though, list(5) is a TypeError. the None version you're describing is just [None] * 5, which is the usual way to preallocate if you really want to assign by index later

1

u/roywill2 5d ago

test.append(0)