Lesson 5.2: Tuples – Basics and Uses
Introduction:
Tuples are similar to lists but are immutable, meaning their values cannot be changed after creation. They are ideal for storing fixed sets of data and are more memory-efficient than lists. Understanding tuples is important for situations where data integrity is required.
1. Creating Tuples:
-
Tuples are created using parentheses
()or without parentheses.
Examples:
2. Accessing Tuple Elements:
-
Tuples are ordered and can be indexed like lists.
-
Negative indexing is also supported.
Examples:
-
Slicing tuples:
3. Tuple Operations:
-
Concatenation: Combine tuples using
+
-
Repetition: Repeat elements using
*
-
Membership check:
4. Tuple Methods:
-
count(value)– Returns how many times a value appears -
index(value)– Returns the index of the first occurrence
Example:
Practical Tips:
-
Use tuples for fixed data that should not be modified
-
Tuples are faster and more memory-efficient than lists
-
Can be used as keys in dictionaries because they are immutable
Learning Outcome of This Lesson:
-
Understand the concept of tuples and their immutability
-
Create and access tuples efficiently
-
Perform basic tuple operations and use built-in methods
-
Use tuples in scenarios where data should remain unchanged
