Index/Indexing and Counting in Python#
In Python, indexing allows us to refer to individual values in specific data structures using their position.
NOTE: Python (and many other programming languages) are zero-indexed, which means counting for index positions begins at 0.
Python Examples#
Let’s use the example of a list of strings:
# list of string objects
fruits = ["apple", "banana", "blueberry", "cherry"]
# check data type
type(fruits)
We can determine the number of elements in the list using the len() function.
len(fruits)
Remember Python starts at 0 and counts left-to-right. We can access specific values using their position.
# access first value
fruits[0]
# access second value
fruits[1]
# access third value
fruits[2]
Python lists also support negative indexing- we can use negative index values to count right-to-left.
NOTE: Negative indexing starts counting at
-1
# access last value
fruits[-1]
# access next to last value
fruits[-2]
We can also use the .index() method to output the position for specific values (if they are present in the structure).
# return index for cherry
print("The index for cherry is ", fruits.index("cherry"))
# return index for pear
print("The index for pear is ", fruits.index("pear"))
The last line of the program returns an IndexError message because pear is not a value in the list.
Indexing & Strings#
We can also use this index syntax with string objects.
# create string variable
message = "Hello world!"
# return number of characters in string
len(message)
# access first character in string
message[0]
# access last character in string
message[-1]
# test if character x is in string
'x' in message # returns false
# test if symbol % is NOT in string
'%' not in message # returns true
Testing for Membership#
We can test for membership using the in and not in operators.
# test if apple is in list
"apple" in fruits
# test if blueberry is NOT in list
"blueberry" not in fruits
The in and not in operators return Boolean True or False values.
Additional Resources
For more on Python’s membership operators: - W3Schools, Python Membership Operators