List Operations in Python
Lists in Python are versatile and powerful data structures that support a wide range of operations.
Here’s a comprehensive overview of common list operations:
1. Creating Lists
empty_list = []
numbers = [1, 2, 3, 4, 5]
mixed_list = [1, "hello", 3.14, True]
2. Accessing Elements
Indexing: Access elements by their index (0-based).
numbers[0] # Output: 1
mixed_list[1] # Output: "hello"
Negative Indexing: Access elements from the end.
numbers[-1] # Output: 5
mixed_list[-2] # Output: 3.14
3. Slicing
numbers[1:4] # Output: [2, 3, 4]
mixed_list[:2] # Output: [1, "hello"]
mixed_list[2:] # Output: [3.14, True]
4. Modifying Lists
Changing Elements:
numbers[0] = 10
mixed_list[1] = "world"
Adding Elements:
o Append: Add a single element to the end.
[Link](6) # Output: [10, 2, 3, 4, 5, 6]
o Insert: Insert an element at a specific position.
[Link](1, 15) # Output: [10, 15, 2, 3, 4, 5, 6]
o Extend: Add multiple elements to the end.
[Link]([7, 8]) # Output: [10, 15, 2, 3, 4, 5, 6, 7, 8]
5. Removing Elements
Remove: Remove the first occurrence of a value.
[Link](15) # Output: [10, 2, 3, 4, 5, 6, 7, 8]
Pop: Remove an element at a specific position (default is the last element).
last_element = [Link]() # Output: 8, numbers: [10, 2, 3, 4, 5, 6,
7]
second_element = [Link](1) # Output: 2, numbers: [10, 3, 4, 5, 6,
7]
Clear: Remove all elements.
[Link]() # Output: []
6. List Operations and Functions
Length: Get the number of elements in a list.
len(numbers) # Output: 7
Check Membership:
4 in numbers # Output: True
10 not in numbers # Output: False
Count: Count occurrences of a value.
[Link](3) # Output: 1
Index: Find the first occurrence of a value.
[Link](4) # Output: 2
7. Sorting and Reversing
Sort: Sort the list in ascending order (in-place).
[Link]() # Output: [2, 3, 4, 5, 6, 7, 10]
[Link](reverse=True) # Output: [10, 7, 6, 5, 4, 3, 2]
Sorted: Return a new sorted list.
sorted_numbers = sorted(numbers) # Output: [2, 3, 4, 5, 6, 7, 10]
Reverse: Reverse the elements of the list (in-place).
[Link]() # Output: [10, 7, 6, 5, 4, 3, 2]
8. List Comprehensions
squares = [x**2 for x in range(5)] # Output: [0, 1, 4, 9, 16]
even_numbers = [x for x in numbers if x % 2 == 0] # Output: [10, 6, 4, 2]
9. Copying Lists
Shallow Copy:
copied_list = [Link]() # or
copied_list = numbers[:]
Deep Copy (for nested lists, using copy module):
import copy
deep_copied_list = [Link](nested_list)
These operations provide a robust set of tools for manipulating and interacting with lists in
Python