For loop with data unpacking #
When iterating over a sequence or collection in Python using a for loop, you can use data unpacking to assign the individual elements of each item to separate variables. This allows you to conveniently access and work with the individual components of the items within the loop.
Here's an example to illustrate data unpacking within a for loop:
students = [
('John', 25, 'Math'),
('Jane', 22, 'Science'),
('Michael', 24, 'English')
]
for student in students:
name, age, subject = student
print(f"Name: {name}, Age: {age}, Subject: {subject}")
We can even make it shorter by unpacking the data within for loop statements, like so:
for name, age, subject in students:
print(f"Name: {name}, Age: {age}, Subject: {subject}")
Exercise #
Unpack the data to print the messages instead of accessing the data with the indexes.
Tests #
- Unpack the data into variables
name,age, andsubjectrespectively
Getting Started with Python
Data Types
Python Functions
Statements in Python
Basic Debugging in Python
Basic Algorithm
Object-Oriented Programming
Error Handling
Intermediate Algorithm
Python Modules