0% found this document useful (0 votes)
1 views

Tuples python

Uploaded by

nassima
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
1 views

Tuples python

Uploaded by

nassima
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 1

Key Characteristics of Tuples 1.

Tuples and Nested Structures:

1. Immutable: Once a tuple is created, its contents cannot be changed (no o Tuples can contain other tuples, lists, or any other type of
adding, removing, or modifying items). objects, allowing for nested data structures.

2. Ordered: Elements have a defined order and can be accessed by index. o Even though tuples themselves are immutable, if they contain
mutable objects (like lists), those objects can still be modified.
3. Allow Duplicates: Tuples can contain duplicate elements.
2. Packing and Unpacking:
4. Heterogeneous: Tuples can store elements of any data type, including
other tuples, lists, or mixed types. o Tuples are often used in "packing" multiple values into a single
variable and "unpacking" them back into separate variables.
Tuple Construction:
o Example: (a, b) = (1, 2) unpacks the tuple into a = 1 and b = 2.
• Tuples can be created using parentheses () or the tuple() constructor.
3. Tuple vs List:
Modifying Tuples:
o Tuples are often used for fixed collections of items, while lists
While tuples themselves are immutable, you can: are better for collections that might change.
1. Convert to a List: Convert a tuple to a list, modify the list, and convert it o Tuples are usually more memory efficient than lists because of
back to a tuple. their immutability.
2. Concatenate Tuples: Tuples can be concatenated to create a new tuple, 4. Concatenation and Repetition:
combining elements from multiple tuples.
o You can concatenate tuples using + and repeat them using *.
Useful Tuple Methods:
▪ Example: (1, 2) + (3, 4) gives (1, 2, 3, 4), and (1, 2) * 3
1. count(): Returns the number of occurrences of a specified value. gives (1, 2, 1, 2, 1, 2).
2. index(): Returns the index of the first occurrence of a specified value.
Raises a ValueError if not found.

Deleting a Tuple:

• The del keyword can be used to delete a tuple completely.

Additional Information:

You might also like