Tuples in Python
Python tutorial · PySpark.in
Tuple
A tuple is a collection of items similar to a list, but with one major difference: Tuples are immutable.You cannot change, add, or remove items after creation.Tuples are commonly used when you want to store data that should remain constant.
Syntax
1. Creating a Tuple
A tuple is an ordered, immutable collection of items. It can store different data types.
2. Accessing Tuple Items
Retrieving elements from a tuple using index positions starting from 0.
3. Negative Indexing
Accessing tuple elements from the end using negative index values.
4. Tuple Slicing
Extracting a portion of a tuple using a range of indexes.
5. Tuples are Immutable
Tuple items cannot be added, modified, or removed after creation.
6. You Can Convert Tuple → List → Tuple
A tuple can be temporarily converted to a list for modification and then back to a tuple.
7. Looping Through a Tuple
Using a loop for to access each element in the tuple one by one.
8. Tuple Methods
Tuples have only two built-in methods:
count(): Counts occurrences of a value
index(): Return first index of a value
9. Nested Tuple
A tuple that contains other tuples inside it.
10. Tuple Packing & Unpacking
Tuple Packing :
Storing multiple values together into a single tuple.
Tuple Unpacking :
Assigning tuple items directly into separate variables.
11. Single Item Tuple
A tuple with one element must include a trailing comma to be recognized as a tuple.
More Python tutorials
- What is Python and Why is it used for Data Science and Data Engineering?
- How Does Python Work in the Backend? Internal Working of Python
- Top 30 Python Interview Questions for Data Science
- 3-Month Python Roadmap to Excel in Data Science and Machine Learning
- Python Data Types Explained – A Beginner’s Guide
- test
All tutorials · Try the free PySpark compiler · Practice challenges