Python Lists: A Comprehensive Guide
What is a List?
Lists are a fundamental data structure in Python used to store collections of items. They are:
- Ordered: Elements maintain a defined sequence.
- Mutable: Elements can be modified after creation.
- Defined by: Square brackets
[]
.
Example:
fruits = ['apple', 'banana', 'orange']
print(fruits) # Output: ['apple', 'banana', 'orange']
Accessing Elements in a List
Positive Indexing
a = [10, 20, 30, 40, 50]
print(a[0]) # Output: 10
print(a[4]) # Output: 50
Negative Indexing (Access elements from the end)
a = [1, 2, 3, 4, 5]
print(a[-1]) # Output: 5
print(a[-3]) # Output: 3
Slicing
my_list = [10, 20, 30, 40, 50]
print(my_list[0:3]) # Output: [10, 20, 30]
print(my_list[::2]) # Output: [10, 30, 50]
List Operations
Modifying Elements
numbers = [1, 2, 3, 4, 5]
numbers[2] = 10
print(numbers) # Output: [1, 2, 10, 4, 5]
Adding Elements
numbers.append(6) # Adds at the end
numbers.insert(1, 9) # Insert at index 1
numbers.extend([7, 8]) # Merge another list
print(numbers) # Output: [1, 9, 2, 10, 4, 5, 6, 7, 8]
Removing Elements
numbers.remove(10) # Removes first occurrence
popped = numbers.pop(2) # Removes by index
del numbers[0] # Delete by index
numbers.clear() # Clears entire list
Sorting and Reversing
numbers = [3, 1, 4, 1, 5, 9, 2]
numbers.sort() # Ascending order
numbers.reverse() # Reverse order
print(numbers) # Output: [9, 5, 4, 3, 2, 1, 1]
List Comprehensions
Basic Example (Square of Numbers)
squares = [x**2 for x in range(5)]
print(squares) # Output: [0, 1, 4, 9, 16]
With Condition (Filtering)
even_numbers = [x for x in range(10) if x % 2 == 0]
print(even_numbers) # Output: [0, 2, 4, 6, 8]
With If-Else
labels = ["Even" if x % 2 == 0 else "Odd" for x in range(5)]
print(labels) # Output: ['Even', 'Odd', 'Even', 'Odd', 'Even']
Flatten a List of Lists
matrix = [[1, 2, 3], [4, 5, 6]]
flattened = [num for row in matrix for num in row]
print(flattened) # Output: [1, 2, 3, 4, 5, 6]
Advanced Examples
# Squares for even numbers, cubes for odd numbers
numbers = range(1, 11)
result = [x**2 if x % 2 == 0 else x**3 for x in numbers]
print(result)
# Filtering odd numbers and multiples of 3, adding 1 to odd numbers
numbers = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
result = [x + 1 if x % 2 != 0 else x for x in numbers if x % 3 == 0]
print(result) # Output: [4, 7, 10]
Taking User Input for Lists
List of Integers from User Input
user_input = input("Enter numbers separated by spaces: ")
numbers = [int(num) for num in user_input.split()]
print("List of numbers:", numbers)
List of Strings from User Input
user_input = input("Enter words separated by spaces: ")
words = user_input.split()
print("List of words:", words)
Error Handling for Input
def get_int_list():
while True:
try:
input_string = input("Enter integers separated by spaces: ")
return list(map(int, input_string.split()))
except ValueError:
print("Invalid input. Please enter integers only.")
int_list = get_int_list()
print("The list of integers is:", int_list)
Summary
Operation | Function |
---|---|
Add element | append() , insert() , extend() |
Remove element | remove() , pop() , del |
Modify element | list[index] = value |
Sorting | sort() |
Reversing | reverse() |
Slicing | list[start:end:step] |
Filtering | [x for x in list if condition] |
This guide provides a structured overview of lists, including indexing, slicing, comprehensions, and user input handling. Mastering these concepts will enhance your Python programming efficiency!