user1830189
user1830189

Reputation: 1

How to check if there is an entry that exists in an array/list in Python?

My code is assigning values to names out of a list. I need to know how to retrieve or set a default value if there is not an entry in my list to assign to one of the names. My code so far:

array =[[a],[b],[c],[d]]
no1 = array[0]
no2 =array[1]
no3 =array[2]
no4 =array[3]
# if array[4] exists:
    no5 = array[4]
else
    no5 = 0

I tried-

try:
    array[4]
except ValueError:
    no5 = 0

but it came up as array[4] out of range.

Just to clarify, as my code writing isn't spectacular, basically I am being given three different inputs for a program which should read these inputs and then write the outputs to a file. The problem is that all of the inputs have varying array lengths. So what I'm trying to do is somehow get the program to check if there is an entry for (say) array[4] and if that entry doesn't exist, create entry array[4] and make it equal to zero.

Upvotes: 0

Views: 969

Answers (5)

tacaswell
tacaswell

Reputation: 87376

You are trying to catch the wrong exception type

try:
    no5 = array[4]
except IndexError:
    no5 = 0

A nifty one-line solution for this is to use itertools

import itertools
(no1,no2,no3,no4,no5),_ = zip(*itertools.izip_longest(array[:5],range(5),fillvalue=0))

Upvotes: 0

GreenMatt
GreenMatt

Reputation: 18570

Why not something like the following?

if len(array) > 4:
    no5 = array[4]
else:
    no5 = 0

Upvotes: 0

gefei
gefei

Reputation: 19766

instead of try you can also check the length of the array

def: elem_exists(arr, idx):
   return 0 <= ldx < len(arr)

Upvotes: 0

kindall
kindall

Reputation: 184141

You should be catching IndexError (the actual error being raised by array[4]) rather than ValueError.

Upvotes: 1

g.d.d.c
g.d.d.c

Reputation: 47978

That you went to try and / except is good. If you got an IndexError then you're really close, you just caught the wrong type of error in your except. This would've worked:

try:
    no5 = array[4]
except IndexError:
    no5 = 0

Upvotes: 1

Related Questions