The index() method provides the position of a value within a list. list = ["red","green","blue"] assert list.index("red") == 0 assert list.index("blue") == 2 Note that if the list does not contain the value specified then a ValueError exception will be thrown. For example: list = ["red","green","blue"] try: pos = list.index("purple") == 0 except [...]
Posts Tagged ‘Index’
How to iterate through a list using an index in Python?
December 23rd, 2010
No Comments
Iterating through a list in Python is simple using a for in loop. colours = ["red","green","blue"] for colour in colours: print colour To iterate through the same list using an index we can apply the enumerate() function. colours = ["red","green","blue"] for i, colour in enumerate(colours): print i, colour
