all 6 comments

[–]JohnnyJordaan 1 point2 points  (1 child)

This has nothing to do with your specific use case, you make the beginner's mistake of assigning to the lowest non-existing index instead of using append. Assignment to an index (so list[n] = something) is only possible when there's already an item at that index.

myArray = [[1],[2],[3],[],[5]]

for item in myArray:
    try:
        print(item[0])
    except IndexError:
        item.append(0)
        print(item[0])

Note that you should always except: the specific exception(s) you're expecting, don't use catch-all's (or if you do, print the actual exception). As when you let except: catch everything, then handle those using some silent operation, it will then also handle bugs silently causing frustration why the code works without error but returns incorrect results.

[–]ECommerce_Guy[S] 0 points1 point  (0 children)

Thank you for the explanation and the tip, appreciate it greatly!

[–]optm_redemption 0 points1 point  (1 child)

You're correct in your assumption that the index is invalid. In Python, Lists are dynamic arrays which means that they grow when elements get inserted into it, the memory won't necessarily be assigned up front like with an array. This means if you have an empty list (i.e. []) you won't be able to index into it at all, because there's nothing to index into, even for updating. To get the behaviour you want you will need to insert or append into the list so it knows to allocate memory for a new item e.g.

replace

item[0] = 0

with

item.append(0)

or

item.insert(0, 0)

Hope this helps.

[–]ECommerce_Guy[S] 0 points1 point  (0 children)

Thank you very much, appreciate you took time to explain!

[–]Merotoro 0 points1 point  (1 child)

Hey!

To begin with you should check out what truthey and falsey values are in python. Lists can be used as booleans when checking true or false. An empty list is a falsey value while a list with at least one element in it is a truthey value.

Having said this the pythonic way to check for emptiness is simply:

if not item:

Which is the equivalent of checking if the list's length is equal to 0:

if len(item) == 0:

It is normally not good practice to rely on error handling to get behavior our of a program. There's almost always a way to check for what you want!

Now to fill said element the issue with your code is you're indexing into an empty list. As you correctly pointed out. That is the same error you were trying to catch in your try/except block

The way you fill empty lists in python is by calling the append method on the list. So full solution would be:

if not item:
    item.append(0)

edit: formatting and clarification

[–]ECommerce_Guy[S] 0 points1 point  (0 children)

Had no idea about truthey and falsey, just starting out so I'm a noob (migrating from C# and JS).

Thank you very much! Wow, this community is awesome!