Tuples
Tuples
In Python, a tuple is a collection of elements that is ordered and immutable. Tuples are similar to lists, but the main difference is that tuples cannot be modified once created, whereas lists can be modified (they are mutable). Tuples are denoted by parentheses `()`, and the elements inside a tuple are separated by commas.
Key features of tuples:
1. Ordered:
Tuples maintain the order of elements, meaning the order in which elements are added to the tuple is preserved.
2. Immutable:
Once a tuple is created, its elements cannot be changed or modified. You can't add, remove, or modify elements.
3. Mixed Data Types:
Tuples can contain elements of different data types, such as integers, strings, floats, or even other tuples.
Here's how you can create a tuple:
```python
my_tuple = (1, "hello", 3.14)
```
You can also create a tuple without parentheses (this is known as tuple packing):
```python
my_tuple = 1, "hello", 3.14
```
To access elements of a tuple, you use indexing, similar to how you access elements in a list:
```python
print(my_tuple[0]) # Output: 1
print(my_tuple[1]) # Output: "hello"
```
Tuples are commonly used when you want to store related pieces of information together. For example, you might use a tuple to represent the coordinates of a point in 2D space:
```python
point = (3, 5) # x-coordinate is 3, y-coordinate is 5
```
Tuples are also used in functions to return multiple values, as a function can only return a single value, but that value can be a tuple containing multiple elements.
```python
def get_coordinates():
return 3, 5
x, y = get_coordinates()
print("x-coordinate:", x) # Output: x-coordinate: 3
print("y-coordinate:", y) # Output: y-coordinate: 5
```
In summary, tuples in Python are a useful data structure when you want to group related data together in an ordered and immutable manner.
Comments
Post a Comment