Immutable Data Type, Tuple
A tuple is a data type in Python used to store multiple values in a specific order, similar to a list. However, unlike lists, tuples are immutable, meaning their contents cannot be changed after creation.
This immutability makes tuples ideal for storing fixed data, such as coordinates of a specific location or color values.
How do you define a tuple?
A tuple is created by enclosing elements in parentheses () and separating each element with a comma ,.
my_tuple = (1, 2, 3) print(my_tuple) # (1, 2, 3)
You can also define a tuple without parentheses by simply separating the values with commas.
my_tuple = 1, 2, 3 print(my_tuple) # (1, 2, 3)
How do you use a tuple?
Tuples are used to safely store values in a program that should not change.
For example, in a map-related program, you can use a tuple to store the latitude and longitude of a specific location.
# Latitude and longitude of New York coordinates = (40.7128, 74.0060) # Print the first element, 40.7128 print("Latitude of New York:", coordinates[0]) # Print the second element, 74.0060 print("Longitude of New York:", coordinates[1])
Lessons in this chapter · List and Tuple data types for storing data in sequence
- 1. How to Store Ordered Data List
- 2. How to Utilize Values in a List
- 3. List IndexError Exception Handling
- 4. How to Concatenate, Repeat, and Determine the Length of Lists
- 5. Adding Elements with append() and insert()
- 6. Multiple-choice quiz
- 7. Comparing List Concatenation and Element Addition in Python
- 8. Removing Elements with the del Keyword and pop() Function
- 9. Removing an Element with a Specific Value using remove() Function
- 10. Using the clear() Function to Remove All Values in a List
- 11. Sorting List Elements with the sort() Function
- 12. How to Check if a List Contains a Specific Element
- 13. Multiple-choice quiz
- 14. Immutable Data Type, Tuple
- 15. Immutability of Tuples and Exception Handling
- 16. Accessing Specific Elements with Tuple Indexing
- 17. Selecting a Portion of a Tuple with Slicing
- 18. How to Perform Operations on Tuples
- 19. Coding Quiz - Sorting Lists
- 20. Multiple-choice quiz
- 21. Fill-in-the-blank quiz
What is the correct characteristic of a tuple?
It is a mutable data type
It is an immutable data type
It is an unordered data type
You can add elements to it
Lecture
AI Tutor
Design
Upload
Notes
Favorites
Help