a=['123','2',4] b=a[4] or 'sss' print b
I want to get a default value when the list index is out of range (here: 'sss'
).
How can I do this?
“List index out of range” error occurs in Python when we try to access an undefined element from the list. The only way to avoid this error is to mention the indexes of list elements properly.
You'll get the Indexerror: list index out of range error when you try and access an item using a value that is out of the index range of the list and does not exist. This is quite common when you try to access the last item of a list, or the first one if you're using negative indexing.
Answer. Answer: The Default Value is the value that a new record starts out with. You can change it if you want, but Access will create new records with this value.
To solve the “index error: list index out of range” error, you should make sure that you're not trying to access a non-existent item in a list. If you are using a loop to access an item, make sure that the loop accounts for the fact that lists are indexed from zero.
In the Python spirit of "ask for forgiveness, not permission", here's one way:
try: b = a[4] except IndexError: b = 'sss'
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With