Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Getting a default value on index out of range in Python [duplicate]

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?

like image 977
zjm1126 Avatar asked Apr 04 '10 14:04

zjm1126


People also ask

How do I fix index out of range in Python?

“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.

What will happen if you try to use an index that is out of range for a list Python?

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.

What is the default value of index?

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.

How do I get rid of index errors?

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.


1 Answers

In the Python spirit of "ask for forgiveness, not permission", here's one way:

try:     b = a[4] except IndexError:     b = 'sss' 
like image 118
Thomas Avatar answered Oct 02 '22 21:10

Thomas