In Python, list
, tuple
, and range
are three types of data structures used to store collections of items. Here are the main differences between them:
1. List
-
Type:
list
-
Mutable (can be changed after creation).
-
Can contain items of any data type (mixed types allowed).
-
Can be modified: items can be added, removed, or changed.
my_list = [1, 2, 3]
my_list.append(4) # [1, 2, 3, 4]
my_list[0] = 10 # [10, 2, 3, 4]
2. Tuple
-
Type:
tuple
-
Immutable (cannot be changed after creation).
-
Used for data that should not be modified.
-
Faster and more memory-efficient than lists.
my_tuple = (1, 2, 3)
# my_tuple[0] = 10 # Error: tuple is immutable
3. Range
-
Type:
range
-
A lazy object (doesn't generate all values immediately but computes them when needed).
-
Commonly used in loops (
for
loop). -
Efficient for generating sequences of numbers.
my_range = range(0, 5) # 0 to 4
print(list(my_range)) # [0, 1, 2, 3, 4]
Quick Comparison Table
Feature | List | Tuple | Range |
---|---|---|---|
Mutable | Yes | No | No |
Indexable | Yes | Yes | Yes |
Can be changed | Yes | No | No |
Iterable | Yes | Yes | Yes |
Memory-efficient | Less so | Yes | Very efficient |
Data types | Mixed | Mixed | Numbers only |
Example | [1,2,3] |
(1,2,3) |
range(0,3) |
When to Use:
-
Use a list if you need to modify the data.
-
Use a tuple if the data should remain constant.
-
Use range when generating number sequences, especially in loops.
0 Comments