Python - Tupple
In Python, a tuple is an ordered, immutable sequence of elements of different data types, separated by commas and enclosed in parentheses. Once a tuple is created, you cannot modify its values. Tuples are similar to lists, but they are usually used to store related, heterogenous data such as coordinates, color codes, etc. Tuples are often used for data integrity and optimization purposes as they are faster and consume less memory than lists, especially for large collections of data. You can access the elements of a tuple using indexing or slicing, just like a list.
Here's an example of using a tuple in Python:
Suppose we want to create a program that takes in a list of student names along with their corresponding grades, and returns a list of students who passed with a grade of at least 60. We can use a tuple to store the student's name and grade as a single unit of data.
# Create a list of student names and grades
students = [("Alice", 85), ("Bob", 50), ("Charlie", 72), ("Dave", 90), ("Eve", 65)]
# Create an empty list to store the names of passing students
passing_students = []
# Iterate over the list of students
for student in students:
# Check if the student passed (grade of at least 60)
if student[1] >= 60:
# Add the student's name to the list of passing students
passing_students.append(student[0])
# Print the list of passing students
print("Passing students:", passing_students)
In this example, we create a list of tuples, where each tuple contains the name of a student and their corresponding grade. We then iterate over the list of tuples, checking if each student's grade is at least 60. If a student passed, we add their name to a new list of passing students. Finally, we print out the list of passing students.
Note that we access the name and grade components of each tuple using their indices, student[0] and student[1], respectively. This is because tuples are indexed starting from 0, just like lists.
Here's another example of a tuple in Python:
# Create a tuple with information about a book
book_info = ("The Great Gatsby", "F. Scott Fitzgerald", 1925, 218)
# Print the tuple
print(book_info)
# Access individual elements of the tuple
print("Title:", book_info[0])
print("Author:", book_info[1])
print("Year:", book_info[2])
print("Number of pages:", book_info[3])
# Try to modify an element of the tuple (will result in an error)
book_info[2] = 1926
In this example, we create a tuple called book_info that contains information about a book, including its title, author, year of publication, and number of pages. We then print the tuple and access individual elements using indexing. Finally, we try to modify an element of the tuple, but receive an error message because tuples are immutable and cannot be modified once they are created.