Skip to content

Instantly share code, notes, and snippets.

@Tset-Noitamotua
Last active February 28, 2017 12:30
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save Tset-Noitamotua/e048266827c8ffc56ad461ad38a382d7 to your computer and use it in GitHub Desktop.
Save Tset-Noitamotua/e048266827c8ffc56ad461ad38a382d7 to your computer and use it in GitHub Desktop.
Python things to remember

HOW TO reliably get index of an iterable's element

To get index of element in a list (or other iterable e.g. dict) reliably --> use enumarate(iterable)! Don't use index()! See below why you should avoid to use index():

nums = [1, 2, 2, 3]

>>> for number in nums:
...     print('index, number:', nums.index(number), number)

# output:
# ('index, number:', 0, 1)
# ('index, number:', 1, 2)
# ('index, number:', 1, 2)    # This is NOT what we want!!!
# ('index, number:', 3, 3)

>>> for index, number in enumerate(nums):
...     print('index, number:', index, number)

# output:
# ('index, number:', 0, 1)
# ('index, number:', 1, 2)
# ('index, number:', 2, 2)   # Yeah, that's what we want!!!
# ('index, number:', 3, 3)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment