🐍 List in Python
Understanding Python Lists with Examples
1. What is a List?
[10, 20, 30, 40, 50]
2. Creating a List
numbers → [10, 20, 30, 40]
names → ['Rahul', 'Amit', 'Priya']
mixed → [10, 'Python', 3.14, True]
empty → []
3. Important Properties of a List
| Property | Description |
|---|---|
| Ordered | Elements maintain their insertion order. |
| Mutable | Elements can be changed after creation. |
| Allows duplicates | The same value can appear multiple times. |
| Heterogeneous | A list can contain different data types. |
| Indexed | Every element has a position/index. |
4. List Indexing
Python uses zero-based indexing. Therefore, the first element has index 0.
Apple
Banana
Orange
5. List Slicing
Slicing is used to extract a portion of a list.
[20, 30, 40]
[10, 20, 30]
[30, 40, 50]
6. Changing List Elements
[10, 200, 30, 40]
7. Adding Elements to a List
[10, 20, 30, 40]
append() adds one element at the end of the list.
[10, 15, 20, 30]
insert(index, value) adds an element at a specific position.
8. Removing Elements
[10, 20, 40]
[10, 20, 30]
9. Important List Methods
| Method | Purpose |
|---|---|
| append() | Adds an element at the end. |
| insert() | Adds an element at a specified position. |
| remove() | Removes a specified value. |
| pop() | Removes an element using its index. |
| clear() | Removes all elements. |
| sort() | Sorts the list. |
| reverse() | Reverses the list. |
| count() | Counts occurrences of a value. |
| index() | Returns the index of a value. |
10. Sorting a List
[10, 20, 30, 40, 50]
[50, 40, 30, 20, 10]
11. Traversing a List
10
20
30
40
50
12. List Length
5
13. List Comprehension
[1, 4, 9, 16, 25]
14. Example: Student Marks
Total = 404
Average = 80.8
15. Quick Revision
✔ List is mutable
✔ List uses [ ] brackets
✔ Index starts from 0
✔ Negative indexing is supported
✔ Duplicate values are allowed
✔ Different data types can be stored
✔ List supports slicing
✔ Lists provide many built-in methods