Lists in Python
A list in Python is a collection of items. It is ordered and changeable, so we can add, remove or change items after creating it. Lists are very flexible. They can hold elements of different data types (like integers, strings, floats, even other lists).
Lists help us store multiple values in a single variable. We use
square brackets
[]
to define a list.
In simple words:
A list in Python is a collection of items which is:
- Ordered (elements have a defined position)
- Mutable (we can change elements after creation)
- Allows duplicate values
Syntax:
list_name = [item1, item2, item3, ...]
Example 1: Creating and accessing a list
fruits = ["apple", "banana", "cherry", "banana"]
print(fruits)
Output:
['apple', 'banana', 'cherry', 'banana']
Explanation:
- We created a list named
fruitswith 4 items. - Lists allow duplicate items, so "banana" appears twice.
Example 2: List with mixed data types
my_data = [25, "ShikshaSanchar", 3.14, True]
print(my_data)
Output:
[25, 'ShikshaSanchar', 3.14, True]
- This list contains an integer, string, float, and boolean.
- Python lists can store different types of data together.
Advantages of Lists
- Flexible: We can store different types of data in a single list (like numbers, strings, boolean). Same as example 2.
- Mutable: We can change, add, or remove items easily after creating the list.
Example Modifying a list:
numbers = [10, 20, 30, 40] numbers[2] = 99 print(numbers)Output:
[10, 20, 99, 40]
Explanation:
- Lists are mutable, so we changed index 2 value from 30 to 99.
- Ordered: Items are stored in the same order as we add them. This helps us retrieve data by position.
- Supports powerful features like loops and list comprehension for quick processing.
- We can store even other lists inside a list (nested lists), making it very versatile.
Disadvantages of Lists
- If the list becomes very large, searching for an item can be slow.
- Because lists can store any type of data, mistakes like mixing wrong data types can happen, which may cause errors later.
- It takes more memory compared to simple variables, especially when storing large data.
Common List Methods:
| Method | Description |
|---|---|
append() |
Adds an item at the end. |
insert() |
Inserts item at given position. |
remove() |
Removes first occurrence of item. |
pop() |
Removes and returns item at given position (last by default). |
sort() |
Sorts the list. |
reverse() |
Reverses the list. |
To learn these methods in detail with examples, click here.
Summary:
- List is a mutable, ordered collection in Python.
- Allows duplicate elements and different data types.
- Very flexible and widely used to handle groups of related data.
- We can use many built-in methods to work with lists.