1. What is a List?
- A list is a collection of items that are ordered, mutable (changeable), and allow duplicate elements.
- Lists are one of the most versatile data structures in Python.
- Lists are defined using square brackets
[].
2. List Operations
1. Accessing Elements
- Use indexing to access individual elements in a list.
- Python uses zero-based indexing (the first element has index
0).
2. Slicing
- Extract a sublist using a range of indices.
- Syntax:
list[start:stop:step]
3. Modifying Elements
- Lists are mutable, so you can change their elements.
4. Adding Elements
- Use
append()to add an element to the end of the list. - Use
insert()to add an element at a specific position. - Use
extend()to add multiple elements from another list.
5. Removing Elements
- Use
remove()to remove the first occurrence of a value. - Use
pop()to remove an element at a specific index (or the last element if no index is provided). - Use
delto delete an element or a slice of elements. - Use
clear()to remove all elements from the list.
6. Finding Elements
- Use
index()to find the index of the first occurrence of a value. - Use
into check if an element exists in the list.
7. Sorting
- Use
sort()to sort the list in place (modifies the original list). - Use
sorted()to return a new sorted list (does not modify the original list).
8. Reversing
- Use
reverse()to reverse the list in place.
9. Length
- Use
len()to find the number of elements in a list.
3. List Comprehensions
- A concise way to create lists using a single line of code.
- Syntax:
[expression for item in iterable if condition]
4. Nested Lists
- A list can contain other lists, creating a multi-dimensional structure.
5. Additional Examples
-
Creating a List:
-
Adding Elements:
-
Removing Elements:
-
Sorting:
-
List Comprehension:
6. Best Practices
- Use list comprehensions for concise and readable code.
- Avoid modifying a list while iterating over it.
- Use
append()instead of+for adding elements to a list (more efficient).