Lecture 2.1: Lists and Tuples
What is a List?
In Python data structure, a list refers to a collection of items that are ordered and malleable, i.e., they can be changed.
Lists are heterogeneous in nature, as they can contain elements of different data types such as integer, string, or even another list.
syntax:
my_list = [1, 2, 3, "apple", 4.5]
What is a Tuple?
Tuple refers to a structured set of elements that are nevertheless immutable and thus cannot be modified post-creation.
syntax:
my_tuple = (1, 2, 3, "apple", 4.5)
Feature | List | Tuple |
---|---|---|
Feature | List | Tuple |
Mutability | Mutable (can change) | Immutable (unchangeable) |
Syntax | [ ] | ( ) |
Usage | When frequent changes are needed | When data integrity is crucial |
List and Tuple Operations:
Indexing
Both lists and tuples are indexed, starting at 0 for the first element.
Accessing Items:
my_list = [10, 20, 30]
print(my_list[1]) # Output: 20
my_tuple = (10, 20, 30)
print(my_tuple[1]) # Output: 20
Slicing:
You can extract specific elements of a list, or a tuple by using slicing.
Syntax: [start:end:step]
my_list = [10, 20, 30, 40, 50]
print(my_list[1:4]) # Output: [20, 30, 40]
print(my_list[::2]) # Output: [10, 30, 50]
my_tuple = (10, 20, 30, 40, 50)
print(my_tuple[1:4]) # Output: (20, 30, 40)
Iteration:
Elements can be traversed by iterating over them in the for loops.
- Example with a list:
for item in [1, 2, 3]:
print(item)
# Output:
# 1
# 2
# 3
- Example with a Tuple:
for item in (4, 5, 6):
print(item)
# Output:
# 4
# 5
# 6
Built-in Functions:
Python contributes with quite a few built-in functions that are helpful for both lists and tuples.
len()
Returns the total number of elements in the list or tuple.
Example:
my_list = [1, 2, 3]
print(len(my_list)) # Output: 3
my_tuple = (4, 5, 6)
print(len(my_tuple)) # Output: 3
min()
Returns the smallest element in the list or tuple.
Example:
my_list = [10, 20, 5, 40]
print(min(my_list)) # Output: 5
my_tuple = (100, 200, 50)
print(min(my_tuple)) # Output: 50
max()
Returns the largest element in the list or tuple.
Example:
my_list = [10, 20, 5, 40]
print(max(my_list)) # Output: 40
my_tuple = (100, 200, 50)
print(max(my_tuple)) # Output: 200
Thanks for this great breakdown of lists and tuples in Python! I’ve always found it interesting how they each have their strengths—lists for flexibility and tuples for reliability. The examples really help solidify the concepts too. Quick question—when dealing with larger datasets, do you tend to favor one structure over the other?
I came across this blog at https://sebbie.pl/tag/python/ that dives into more Python topics. It’s great to see similar content that delves a bit deeper into advanced stuff. Worth checking out for anyone wanting to explore further!
Thanks again for such an informative post!
Thank uh !!
When dealing with larger datasets, the choice of structure often depends on the type of data, the operations needed, and the system’s performance constraints.