Index

Yesterday I realised how useful try/except is, e.g.:

x = [1,2,3].index(4)

gives:

ValueError: 4 is not in list

So there are two ways to use index:

#first way
if val in lst:
    x = lst.index(val)
else:
    print("x not in lst")
#second way
try:
    x = lst.index(val)
except ValueError:
    print("x not in lst")
Advertisements

2 thoughts on “Index

    1. Thank you! Pascal-born and C-raised as a student, it does not come natural to use try for flow control. But a change of habits is worth it in Python I guess.

      Like

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s