Python Lists
In Python, a list is a versatile and mutable data type that allows you to store a collection of elements. Lists are defined by enclosing elements in square brackets [ ]
and separating them with commas.
1. Creating Lists
Lists can contain elements of different data types.
# Empty list
empty_list = []
# List with elements
numbers = [1, 2, 3, 4, 5]
names = ["Alice", "Bob", "Charlie"]
mixed_types = [1, "two", 3.0, True]
2. Accessing Elements
Elements in a list are accessed using zero-based indexing.
numbers = [1, 2, 3, 4, 5]
first_element = numbers[0] # 1
third_element = numbers[2] # 3
3. List Slicing
You can extract a sublist (slice) from a list using slicing.
numbers = [1, 2, 3, 4, 5]
sub_list = numbers[1:4] # [2, 3, 4]
4. List Methods
Python provides various built-in methods for list manipulation.
numbers = [1, 2, 3]
numbers.append(4) # [1, 2, 3, 4]
numbers.extend([5, 6]) # [1, 2, 3, 4, 5, 6]
numbers.insert(2, 10) # [1, 2, 10, 3, 4, 5, 6]
numbers.remove(3) # [1, 2, 10, 4, 5, 6]
popped_value = numbers.pop() # Removes and returns the last element (6)
5. List Concatenation
Lists can be concatenated using the +
operator.
list1 = [1, 2, 3]
list2 = [4, 5, 6]
combined_list = list1 + list2 # [1, 2, 3, 4, 5, 6]
6. List Comprehension
A concise way to create lists using a single line of code.
squares = [x**2 for x in range(1, 6)] # [1, 4, 9, 16, 25]
7. Length of a List
The len()
function returns the number of elements in a list.
numbers = [1, 2, 3, 4, 5]
length = len(numbers) # 5
8. Checking Membership
The in
and not in
operators check whether an element is present in a list.
fruits = ["apple", "banana", "orange"]
has_apple = "apple" in fruits # True
has_mango = "mango" not in fruits # True
9. Sorting a List
The sort()
method sorts the elements of a list in ascending order.
numbers = [4, 2, 1, 3, 5]
numbers.sort() # Sorts in-place: [1, 2, 3, 4, 5]
10. Reversing a List
The reverse()
method reverses the elements of a list in-place.
numbers = [1, 2, 3, 4, 5]
numbers.reverse() # Reverses in-place: [5, 4, 3, 2, 1]
Lists are a fundamental data structure in Python, widely used for storing and manipulating collections of items. Understanding how to create, access, and manipulate lists is essential for many programming tasks.