Tuples in Python are similar to lists but with one key difference: tuples are immutable, meaning once they are created, their elements cannot be changed, added, or removed. Tuples are useful for representing fixed collections of items.
Creating Tuples
Tuples are created by placing comma-separated values inside parentheses ()
.
Accessing Elements
You can access elements in a tuple using indexing, just like with lists.
Slicing Tuples
Slicing allows you to get a subset of the tuple.
Tuple Operations
Concatenation
You can concatenate two or more tuples using the +
operator.
Repetition
You can repeat tuples using the *
operator.
Tuple Methods
Since tuples are immutable, they have fewer methods compared to lists. The most common tuple methods are count()
and index()
.
count()
Returns the number of times a specified value occurs in a tuple.
index()
Returns the index of the first occurrence of a specified value.
Tuple Packing and Unpacking
Packing
Packing is the process of creating a tuple from multiple values.
Unpacking
Unpacking is the process of assigning the values of a tuple to multiple variables.
Nested Tuples
Tuples can contain other tuples as elements, allowing for nested structures.
Summary
- Creating Tuples: Use parentheses
()
or just commas. - Accessing Elements: Use indexing and slicing.
- Tuple Operations: Concatenation and repetition.
- Tuple Methods:
count()
andindex()
. - Packing and Unpacking: Create and extract multiple values.
- Nested Tuples: Tuples can contain other tuples.
Tuples are ideal for fixed collections of items and can be used effectively in many scenarios, especially where immutability is required.
Comments
Post a Comment