Lesson 5.1: Lists – Creation, Indexing, Methods
Introduction:
Lists are one of the most versatile data structures in Python. They allow you to store multiple items in a single variable, maintain order, and perform various operations like adding, removing, and modifying elements. Mastering lists is essential for efficient data handling.
1. Creating Lists:
-
Lists are created using square brackets
[]and can contain elements of any data type.
Examples:
2. Accessing and Indexing:
-
Lists are ordered, and elements can be accessed using their index.
-
Indexing starts from
0.
Examples:
-
Slicing lists:
3. Common List Methods:
| Method | Description |
|---|---|
append() |
Adds an element at the end of the list |
insert() |
Inserts an element at a specified position |
remove() |
Removes the first occurrence of a value |
pop() |
Removes and returns an element at a given index (default last) |
clear() |
Removes all elements from the list |
index() |
Returns the index of the first occurrence of a value |
count() |
Returns the number of times a value appears in the list |
sort() |
Sorts the list in ascending order (can use reverse=True) |
reverse() |
Reverses the order of elements |
Example – Using Methods:
Practical Tips:
-
Lists can store heterogeneous data (different types together).
-
Use slicing and indexing to access sub-parts efficiently.
-
Apply built-in methods to manipulate lists instead of writing manual loops.
Learning Outcome of This Lesson:
-
Understand how to create and access lists
-
Perform indexing, slicing, and sub-list extraction
-
Apply common list methods for data manipulation
-
Use lists effectively to store and manage multiple values
