-1

In python we have get() method in dictionary to get values safely. Any way to achieve this in list?

my_dict = {'fruit':'apple','colour':'black'}
my_dict.get('colour','None') #returns black
my_dict.get('veg','None')  #returns None

my_list = ['apple','fish','blue','bottle','gold']
colour = my_list[2]
print(colour)  #returns blue
value = my_list[7] #gives error. Expected: need to return default value as None.

In my case length of my_list is not constant.Values are getting populated in runtime.If i try to get the index which is not present in the my_list it should return default value as None. How to get the default values when list is not having requested index.?

bluebud
  • 183
  • 1
  • 1
  • 10
  • please check https://stackoverflow.com/questions/5125619/why-doesnt-list-have-safe-get-method-like-dictionary – Epsi95 Dec 10 '21 at 08:42

1 Answers1

0

Use try-except block -

try:
    value = my_list[7]
except:
    print("Value doesn't exist")

In case, the try statement has an error, it switches to the except block

PCM
  • 2,881
  • 2
  • 8
  • 30