Skip to content

Instantly share code, notes, and snippets.

@tomthorogood
Created February 13, 2012 13:43
Show Gist options
  • Select an option

  • Save tomthorogood/1817052 to your computer and use it in GitHub Desktop.

Select an option

Save tomthorogood/1817052 to your computer and use it in GitHub Desktop.
Return position of element in Python tuple
def index_in_tuple(value, iterable):
return [num for num, val in enumerate(iterable) if val is value][0]
# Works for lists too, but those already have this functionality built in.
# How it works:
# value = "three"
# iterable = ("one", "two", "three", "four")
# enumerate(iterable) => ( (0, "one"), (1, "two") ... )
# num for num, val => 0, "one" [...] # num refers to the '0' in this case
# ..."if val is value" => but only if "one" is "three" (which it's not)
# after evaluating, we'd have something like: return [2][0], which is just "2", as an int.
# the [0] is not necessary if you want a list of all positions of an element within a tuple:
# ("one", "two", "three", "four", "three") would be evaluated to [2,4]
# The current code would return only the 2, but if you wanted all values, you could remove the [0].
# iterable = ("one", "two", "eight", "eleven")
# index = index_in_tuple("eight", iterable)
# segment = iterable[index:] # ("eight", "eleven")
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment