Python List
Python Lists
In Python, lists are used to store multiple items in a single variable. Lists are one of the most versatile data structures in Python.
What is a List?
A list is a collection of ordered, changeable, and indexed items. Lists are written with square brackets.
# Example: Python List
my_list = [1, 2, 3, 4, 5]
print(my_list) # Output: [1, 2, 3, 4, 5]
List Operations
Python lists come with various operations like indexing, slicing, adding, and removing elements.
# Indexing
my_list = [10, 20, 30, 40, 50]
print(my_list[0]) # Output: 10 (first element)
# Slicing
print(my_list[1:4]) # Output: [20, 30, 40]
# Adding Elements
my_list.append(60)
print(my_list) # Output: [10, 20, 30, 40, 50, 60]
# Removing Elements
my_list.remove(20)
print(my_list) # Output: [10, 30, 40, 50, 60]
Common List Methods
- append(): Adds an item to the end of the list.
- remove(): Removes the first occurrence of a value from the list.
- pop(): Removes and returns an item at a specified index.
- sort(): Sorts the list in ascending order.
- reverse(): Reverses the order of the list.