Introduction to Python Lists
Python lists are versatile data structures that allow you to store and manipulate collections of items. They are ordered, mutable, and can hold elements of different data types. Lists are one of the most fundamental and widely used data structures in Python.
Understanding Lists
A list in Python is defined by enclosing a comma-separated sequence of values within square brackets []
. For example:
fruits = ['apple', 'banana', 'cherry']
numbers = [1, 2, 3, 4, 5]
mixed_list = ['apple', 1, 3.14, True]
In the above examples, fruits
is a list of strings, numbers
is a list of integers, and mixed_list
is a list that contains elements of different data types.
Accessing List Elements
You can access individual elements in a list using their index. Python lists are zero-indexed, meaning the first element has an index of 0, the second element has an index of 1, and so on.
fruits = ['apple', 'banana', 'cherry']
print(fruits[0]) ## Output: 'apple'
print(fruits[1]) ## Output: 'banana'
print(fruits[2]) ## Output: 'cherry'
You can also use negative indices to access elements from the end of the list, where -1 represents the last element, -2 represents the second-to-last element, and so on.
fruits = ['apple', 'banana', 'cherry']
print(fruits[-1]) ## Output: 'cherry'
print(fruits[-2]) ## Output: 'banana'
print(fruits[-3]) ## Output: 'apple'
Common List Operations
Python provides a wide range of operations and methods for working with lists. Some of the most common ones include:
len(list)
: Returns the number of elements in the list.
list.append(item)
: Adds an item to the end of the list.
list.insert(index, item)
: Inserts an item at the specified index.
list.remove(item)
: Removes the first occurrence of the specified item.
list.pop([index])
: Removes and returns the item at the specified index (or the last item if no index is specified).
list.index(item)
: Returns the index of the first occurrence of the specified item.
list.count(item)
: Returns the number of times the specified item appears in the list.
list.sort()
: Sorts the elements of the list in ascending order.
list.reverse()
: Reverses the order of the elements in the list.
These are just a few examples of the many list operations available in Python. Familiarizing yourself with these operations will help you effectively work with lists in your Python programs.