Skip to content

Instantly share code, notes, and snippets.

@systemsoverload
Created February 27, 2014 21:31
Show Gist options
  • Save systemsoverload/9259988 to your computer and use it in GitHub Desktop.
Save systemsoverload/9259988 to your computer and use it in GitHub Desktop.
#Throws exception IndexError
names = [["TJ","Kells"], ["Erin","Wilbur"],["JEFFEREY"]]
for name in names:
first_name = name[0]
last_name = name[1]
print first_name, last_name
#Avoids exception, but if statement is invoked on every loop
names = [["TJ","Kells"], ["Erin","Wilbur"],["JEFFEREY"]]
for name in names:
first_name = name[0]
if len(name) > 1:
last_name = name[1]
else:
last_name = 'Not provided'
print first_name, last_name
#Catches exception ONLY WHEN last name is not present
names = [["TJ","Kells"], ["Erin","Wilbur"],["JEFFEREY"]]
for name in names:
first_name = name[0]
try:
last_name = name[1]
except IndexError:
last_name = "not provided"
print first_name, last_name
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment