Tuples
In Python, a tuple is a collection of ordered and immutable elements, separated by commas and enclosed in parentheses. Once a tuple is created, you cannot change its elements. This makes them useful for storing data that should not be modified, such as a set of configuration values for an application.
Creating a Tuple:
To create a tuple, separate the elements with commas and enclose them in parentheses.
my_tuple = (1, 2, 3, "four")
Accessing Elements:
You can access individual elements of a tuple using indexing. Indexing starts at 0 for the first element and goes up to n-1 for the nth element.
my_tuple = (1, 2, 3, "four")
print(my_tuple[0]) # Output: 1
print(my_tuple[3]) # Output: "four"
Slicing Tuples:
You can also access a range of elements in a tuple using slicing.
my_tuple = (1, 2, 3, "four", 5, 6, 7)
print(my_tuple[1:4]) # Output: (2, 3, "four")
This code will output a new tuple that contains the elements from index 1 (inclusive) to index 4 (exclusive).
Tuple Packing and Unpacking:
Tuple packing is the process of putting elements into a tuple. Tuple unpacking is the opposite, where you take a tuple and assign its elements to separate variables.
my_tuple = 1, 2, 3
print(my_tuple) # Output: (1, 2, 3)
a, b, c = my_tuple
print(a) # Output: 1
print(b) # Output: 2
print(c) # Output: 3
In this example, we first create a tuple called my_tuple by separating the elements with commas. We then unpack the tuple into three separate variables: a, b, and c.
Iterating Over Tuples:
You can iterate over a tuple using a for loop. The loop will execute once for each element in the tuple.
my_tuple = (1, 2, 3, "four")
for element in my_tuple:
print(element)
In this example, we use a for loop to iterate over each element in the my_tuple tuple and print it to the console.
Conclusion
Tuples are a useful data structure in Python for storing collections of ordered and immutable elements. By understanding how to create, access, and iterate over tuples, you can use them effectively in your code.
Basic Topics
- Introduction to Python
- Basic Syntax and Data Types
- Variables and Operators
- Input
- Conditional statements
- Loops
- Functions
- List
- Tuples
- Sets
- Dictionary
- Modules
- Packages
- Exception Handling
- Read/Write Files