Practical Use Cases
Tuples for Returning Multiple Values
Tuples can be used to return multiple values from a function, which can be useful for tasks like unpacking data or representing complex information.
def get_person_info():
name = "LabEx"
age = 5
return name, age
person_name, person_age = get_person_info()
print(f"Name: {person_name}, Age: {person_age}") ## Output: Name: LabEx, Age: 5
Lists for Storing and Manipulating Data
Lists are commonly used to store collections of data that need to be modified, such as shopping lists, to-do lists, or inventory management.
## Creating a shopping list
shopping_list = ["apple", "banana", "orange"]
## Adding an item to the list
shopping_list.append("pear")
## Removing an item from the list
shopping_list.remove("banana")
print(shopping_list) ## Output: ['apple', 'orange', 'pear']
Tuples for Representing Structured Data
Tuples can be used to represent structured data, such as geographic coordinates or database records, where the order and composition of the data is important.
## Representing a geographic coordinate
location = (37.7749, -122.4194)
## Accessing the latitude and longitude
latitude, longitude = location
print(f"Latitude: {latitude}, Longitude: {longitude}") ## Output: Latitude: 37.7749, Longitude: -122.4194
Lists for Iterating and Manipulating Data
Lists are often used in loops and list comprehensions to iterate over and manipulate data.
## Iterating over a list
numbers = [1, 2, 3, 4, 5]
for num in numbers:
print(num) ## Output: 1, 2, 3, 4, 5
## List comprehension to square numbers
squared_numbers = [x**2 for x in numbers]
print(squared_numbers) ## Output: [1, 4, 9, 16, 25]