Python Lists
What is a List?
A list in Python is a versatile data structure that represents an ordered collection of items. It's mutable, meaning you can change its contents after it's created. Lists are defined by enclosing elements within square brackets [] and separated by commas.
Creating a List
Python
my_list = [1, 2, 3, "apple", True]
As you can see, lists can contain items of different data types.
Accessing List Elements
You can access individual elements using their index. Indexing starts from 0.
Python
my_list = [10, 20, 30, 40]
first_element = my_list[0] # Accesses the first element (10)
third_element = my_list[2] # Accesses the third element (30)
Slicing Lists
You can extract a portion of a list using slicing:
Python
my_list = [10, 20, 30, 40, 50]
sublist = my_list[1:4] # Extracts elements from index 1 to 3 (inclusive)
print(sublist) # Output: [20, 30, 40]
Modifying Lists
Lists are mutable, meaning you can change their contents.
Python
my_list = [10, 20, 30]
my_list[1] = 25 # Change the second element
my_list.append(40) # Add an element to the end
my_list.insert(1, 15) # Insert an element at index 1
my_list.remove(20) # Remove the first occurrence of 20
del my_list[0] # Delete the element at index 0
List Methods
Python provides several built-in methods for manipulating lists:
- append(): Adds an element to the end of the list.
- extend(): Appends the elements of another list to the end of the current list.
- insert(): Inserts an element at a specific index.
- remove(): Removes the first occurrence of a specified value.
- pop(): Removes and returns the element at a specific index (or the last element if no index is specified).
- index(): Returns the index of the first occurrence of a specified value.
- count(): Returns the number of occurrences of a specified value.
- sort(): Sorts the list in ascending order.
- reverse(): Reverses the order of the elements in the list.
- clear(): Removes all elements from the list.
Example
Python
my_list = [3, 1, 4, 1, 5, 9]
my_list.sort()
print(my_list) # Output: [1, 1, 3, 4, 5, 9]
my_list.reverse()
print(my_list) # Output: [9, 5, 4, 3, 1, 1]
Important Points
- Lists can contain any data type, including other lists.
- Lists are dynamic, meaning their size can change as elements are added or removed.
- Lists are mutable, so changes made to a list affect the original list.
By understanding these concepts and methods, you can effectively use lists in your Python programs to store and manipulate data.