Header Ads Widget

Ticker

6/random

Python Tuples

Python Tuples


In Python, a tuple is an ordered and immutable collection of elements. Once you create a tuple, you cannot modify its contents. Here are some examples illustrating the use of tuples:


1. Creating Tuples:

   ```python

   point = (3, 5)

   colors = ('red', 'green', 'blue')

   mixed_tuple = (1, 'hello', 3.14, True)

   ```

2. Accessing Elements:

```python

   coordinates = (3, 5)

   x_coordinate = coordinates[0] # 3

   y_coordinate = coordinates[1] # 5

   ```

3. Tuple Unpacking:

   ```python

   dimensions = (10, 20, 30)

   length, width, height = dimensions

   ```

4. Immutability:

```python

   my_tuple = (1, 2, 3)

   # Attempting to modify a tuple will result in an error

   # my_tuple[1] = 5 # Raises Type Error

   ```

5. Using Tuples in Functions:

   ```python

   def return_coordinates():

       return (4, 7)

   x, y = return_coordinates()

   ```

6. Nested Tuples:

```python

   nested_tuple = ((1, 2), ('a', 'b'), (True, False))

   ```

7. Tuple Methods:

   ```python

   numbers = (4, 2, 8, 1, 6)

   min_value = min(numbers)

   max_value = max(numbers)

   ```


These examples cover the basic operations and characteristics of tuples in Python. Tuples are often used when you want to create a collection of elements that should remain constant throughout the program execution.

Post a Comment

0 Comments