torsdag 18 augusti 2022

Python | Avoid IndexError by slicing

"IndexError: list index out of range" can for example be avoided by doing [0:1] instead of [0] 

Let's say you're handling iterators that sometimes are empty and do something like "...if list_ else []". 

You're doing this to avoid trying to access an index that doesn't exist when the list is empty, like this: [][0].


If you don't need the item directly and it's ok to return an iterable, an easier or at least shorter way of returning empty iterable can be to return a sliced version of it. 

[][:1] returns an empty list []

["Test"][:1] returns ["Test"]


Other working examples:[][0:0], [][1:0], [][0:2] [][100:25], [][25:100]

These all return [].




Inga kommentarer:

Skicka en kommentar