How to Make Sure an Index Exists in Python
Indices are used in array variables as markers that designate each value in the array. When you iterate through the array, pulling each value out by its index, some values and their indices may be missing. If your program does not take this possibility into account, it may error out and stop unexpectedly. The solution is to put an index check into your code.
- Difficulty:
- Moderately Easy
Instructions
-
-
1
Open the Python program that contains the array whose index you need to check.
-
2
Go to the variable that contains the array, such as "$myArray."
-
3
Type (under the variable) the following code:
for($x<sizeof($myarray)|if($myArray[$x]){INDEX_EXISTS_ACTION} else {INDEX_DOESN'T_EXIST_ACTION},$x++);
Substitute in the code you want to execute when the index does exist for "INDEX_EXISTS_ACTION" and the code you want to execute when the index does not exist for "INDEX_DOESN'T_EXIST_ACTION" to complete this index existence check.
-
1