In my program, user inputs number n
, and then inputs n
number of strings, which get stored in a list.
I need to code such that if a certain
Could it be more useful for you to use the length of the list len(n)
to inform your decision rather than checking n[i]
for each possible length?
You can try something like this
list = ["a", "b", "C", "d", "e", "f", "r"]
for i in range(0, len(list), 2):
print list[i]
if len(list) % 2 == 1 and i == len(list)-1:
break
print list[i+1];
I need to code such that if a certain list index exists, then run a function.
You already know how to test for this and in fact are already performing such tests in your code.
The valid indices for a list of length n
are 0
through n-1
inclusive.
Thus, a list has an index i
if and only if the length of the list is at least i + 1
.
Using the length of the list would be the fastest solution to check if an index exists:
def index_exists(ls, i):
return (0 <= i < len(ls)) or (-len(ls) <= i < 0)
This also tests for negative indices, and most sequence types (Like ranges
and str
s) that have a length.
If you need to access the item at that index afterwards anyways, it is easier to ask forgiveness than permission, and it is also faster and more Pythonic. Use try: except:
.
try:
item = ls[i]
# Do something with item
except IndexError:
# Do something without the item
This would be as opposed to:
if index_exists(ls, i):
item = ls[i]
# Do something with item
else:
# Do something without the item
It can be done simply using the following code:
if index < len(my_list):
print(index, 'exists in the list')
else:
print(index, "doesn't exist in the list")
A lot of answers, not the simple one.
To check if a index 'id' exists at dictionary dict:
dic = {}
dic['name'] = "joao"
dic['age'] = "39"
if 'age' in dic
returns true if 'age' exists.