Lists
Lists
Here's a comprehensive overview of lists covering their definition, structure, properties, operations,
and more.
Definition of a List
A list is a mutable, ordered collection of elements containing items of any data type (including other
lists). Lists are one of Python's most versatile and commonly used data structures.
List Structure
- Syntax: Lists are defined by placing elements inside square brackets ` []`, separated by commas.
- Indexing: Each element in a list has a position, or index, starting from `0` for the first element and
incrementing by 1. Negative indexing is also supported, where `-1` refers to the last element.
my_list[0] # Output: 1
- Nested Lists: Lists can contain other lists as elements, allowing for multi-dimensional data
structures.
List Properties
1. Mutability:
- Lists are mutable, meaning their elements can be changed after the list is created.
- Example:
my_list = [1, 2, 3]
2. Order:
- Lists maintain the order of elements. The order in which elements are inserted is preserved.
- Example:
- Example:
Creating a List
- Empty List:
empty_list = []
numbers = [1, 2, 3, 4, 5]
- The `list()` function can be used to create a list from an iterable (like a string, tuple, or range).
1. Accessing Elements:
2. Modifying Elements:
3. Adding Elements:
4. Removing Elements:
- `pop()`: Removes and returns the element at a specific index (or the last element if no index is
specified).
5. Concatenating Lists:
6. Repeating Lists:
7. Finding Elements:
9. Copying a List:
- List comprehensions provide a concise way to create lists. It consists of brackets containing an
expression followed by a `for` clause, and optionally followed by `if` clauses.
List Methods
extend() Extends the list by appending all items from another lst.extend([5, 6])
iterable.
pop() Removes and returns the item at the given position (or lst.pop(1) → 'a'
the last item if no index is specified).
list Creates a new list by applying an expression to each [x**2 for x in lst]
comprehension item in an iterable.
sum() Returns the sum of all items in a list (must be numeric). sum(lst) → 10
any() Returns True if any element of the list is True. any([0, 1, 2]) →
True
all() Returns True if all elements of the list are True. all([1, 2, 3]) → True
join() Joins elements of a list into a string, using a separator. ','.join(['a', 'b'])
(Works with list of strings). → 'a,b'
- You can use list comprehensions inside other list comprehensions to work with multi-dimensional
lists.
2. Unpacking Lists:
a, b, c = [1, 2, 3]
print(item)
4. List as Stack:
- Lists can be used as stacks, where you use `append()` to push elements and `pop()` to pop them
off.
stack = []
stack.append('a')
stack.append('b')
5. List as Queue:
- Lists can be used as queues, but operations on the left end of the list are not efficient. For a more
efficient queue, use `collections.deque`.
queue.append(4)
queue.popleft() # Removes 1
- Memory Usage:
- Lists in consume more memory than arrays, as they store references to objects rather than the
objects themselves.
- Performance:
- Appending elements is `O(1)`, but extending or inserting elements can be `O(n)` (linear time).
- Removing elements is `O(n)` because all elements after the removed element must be shifted.
Common Errors with Lists
1. IndexError:
- Example:
lst = [1, 2, 3]
2. TypeError:
- Occurs when performing operations that are not supported between incompatible types.
- Example:
lst = [1, 2, 3]
lst + 'a' # TypeError: can only concatenate list (not "str") to list