Python: Lists
Master the most versatile data structure in Python. Lists allow you to store collections of items, modify them on the fly, and process them efficiently using comprehensions.
Creating Lists
A list is a data structure in Python that is a mutable, ordered sequence of elements. Lists are defined by having values between square brackets [ ], separated by commas. Unlike strings, lists are mutable, meaning you can change their elements after they have been created.
List Initialization
PythonLists can hold any type of data, even mixed types.
Accessing and Modifying Elements
Elements in a list are accessed via their index, starting from 0. You can also use negative indexing, where -1 refers to the last item. Since lists are mutable, you can assign a new value to a specific index.
Index Access and Mutation
PythonGetting and setting values.
List Slicing
Slicing allows you to extract a sub-sequence from a list. The syntax islist[start:stop:step]. The start index is inclusive, while the stop index is exclusive.
Slicing Techniques
PythonCapturing portions of a list.
Methods: Adding Elements
Python provides several ways to add items to a list. Use append()for a single item, insert()to place an item at a specific index, and extend()to add multiple items from another iterable.
Growing a List
PythonMethods to expand your collection.
Methods: Removing Elements
To remove items, you can use remove()(by value), pop()(by index, returns the item), or clear()to empty the list entirely. The delkeyword also works for specific indices or slices.
Shrinking a List
PythonMethods to remove items.
Utility: Search and Sort
Lists can be searched with index()and count(). To put items in order, use sort()(in-place) or the reverse() method.
Organization and Search
PythonManaging order and finding items.
Iteration and Nested Lists
The most common way to process a list is with a for loop. Lists can also contain other lists, creating multidimensional data structures often referred to as matrices or 2D lists.
Looping and Nesting
PythonHandling collections of collections.
List Comprehensions
List comprehensions provide a concise way to create lists. They consist of brackets containing an expression followed by a for clause, then zero or more for or if clauses. They are often faster and more readable than standard loops.
The Power of Expression
PythonGenerating lists on the fly.
Copying: Shallow vs Deep
A simple assignment (b = a) does not copy the list; it only creates a new reference. To truly copy a list, you use the copy() method. However, for nested lists, you need a deep copy to avoid shared references between inner lists.
The Copy Rule
Shallow copies are enough for flat lists, but nested data needs deepcopy.
- Shallow Copy: list.copy() or list[:]. Copies the outer container but nested objects are shared.
- Deep Copy: copy.deepcopy(). Recursively copies everything. No shared state.
- Best Practice: Import the copy module for deep copies.
Copy Behavior
PythonUnderstanding shared references.
Lists as Stacks and Queues
Lists can emulate other data structures. As a Stack (LIFO - Last In, First Out), use append()and pop(). As a Queue (FIFO - First In, First Out), useappend()and pop(0).
Performance Optimization
Using pop(0) on a list is slow because all other elements must be shifted.
- pop(0) is O(n) complexity
- For efficient queues, use collections.deque which allows O(1) removals from the front
- Lists are excellent for stacks (O(1) append and pop)
Data Structures with Lists
PythonEmulating stacks and queues.
Custom Sorting: key and reverse
The sort() method and sorted() function accept a key parameter. This allows you to specify a function that determines the sort logic (e.g., sorting strings by length).
Advanced Sorting
PythonControlling order with lambda functions.
Quiz - Test Your Knowledge
Verify your understanding of Python lists by tackling these eight questions. Pay close attention to slicing rules and the difference between in-place methods and functions.
Knowledge Check
1. How do you add an element to the end of a list?
2. What is the result of [1, 2, 3] + [4, 5]?
3. Which method removes and returns the last item of a list?
4. How do you create a shallow copy of a list named "original"?
5. What is a list comprehension?
6. Which list method is used to sort a list in place?
7. How do you access the last element of a list using negative indexing?
8. Which complexity is typical for list.pop(0) (removing from the front)?