[Link].
in
Python Tuples
1. Introduction to Tuples
• A tuple is a collection that is:
o Ordered
o Immutable (cannot be changed after creation)
o Allows duplicate values
• Tuples are written using Parentheses ( ).
• Tuples elements can be of different data types.
• Tuples can be created by placing comma-separated values inside
parentheses.
2. Tuple Index
• Tuples are indexed starting from 0.
• Negative indexing starts from -1 (last element).
3. Accessing Single Element from Tuple
• Access individual elements using their index.
• Syntax: tuple[index]
4. Accessing Multiple Elements from Tuples (Slicing)
• Slicing allows you to extract a portion of a tuple using a specific range of
indices.
• Syntax: tuple[start : end : step]
1
[Link]
o start: index to begin the slice
o end: index to stop (excluded)
o step: how many steps to skip
Default values based on step:
• If step is positive:
o start defaults to 0
o end defaults to end of tuple
• If step is negative:
o start defaults to -1 (last element)
o end defaults to beginning of tuple
• Examples
2
[Link]
5. Check Item Using in and not in Keywords
• Use in to check if an item exists in the tuple.
• Use not in to check if an item does not exist.
6. Tuple Concatenation and Multiplication
• Use + to join two tuples.
• Use * to repeat a tuple multiple times.
3
[Link]
7. Tuple Length
• Use len() to find how many elements are in a tuple.
8. Creating Single-Element Tuple
• A single element tuple must include a comma.
8. Change Tuple Item
• Tuples are immutable, but you can change their contents by converting
them to a list, modifying it, and converting it back.
9. Unpack Tuples
4
[Link]
• You can assign tuple elements to individual variables using unpacking.
• You can also use * to unpack remaining items:
10. Tuple Constructor
• You can create a tuple from another iterable using the tuple() constructor.