Python: Access List Items
Lists are a fundamental data structure in Python that allow you to store and manipulate collections of items. In this lesson, we will cover how to access individual items in a list using index notation and slicing.
Accessing Individual Items
You can access individual items in a list by using square brackets []
and specifying the index of the item you want to access. Python uses zero-based indexing, so the first item in the list has an index of 0. For example:
fruits = ['apple', 'banana', 'cherry']
print(fruits[0]) # Output: 'apple'
print(fruits[1]) # Output: 'banana'
print(fruits[2]) # Output: 'cherry'
Using Negative Indexing
You can also use negative indexing to access items from the end of the list. For example, fruits[-1]
will access the last item in the list, fruits[-2]
will access the second-to-last item, and so on.
Slicing Lists
In addition to accessing individual items, you can also access a sublist (or slice) of a list by using the slicing notation. Slicing allows you to specify a range of indices to extract a portion of the list. For example:
print(fruits[1:3]) # Output: ['banana', 'cherry']
print(fruits[:2]) # Output: ['apple', 'banana']
print(fruits[1:]) # Output: ['banana', 'cherry']
print(fruits[:]) # Output: ['apple', 'banana', 'cherry']
Conclusion
Accessing list items in Python is straightforward using index notation and slicing. By understanding these concepts, you can work with lists effectively and manipulate their contents as needed in your programs.