Course Content
Python Indentation, Comments and Variables
0/2
Object Oriented Programming in Python
0/1
Exception Handling in Python
0/1
Sending emails with Python
0/1
Unit test in python programming
0/1
Python programming (zero to advance!!!)
About Lesson

PYTHON TUPLES

In Python, a tuple is a data structure similar to a list, but with one key difference: tuples are immutable, meaning they cannot be modified after creation. Once a tuple is created, its elements cannot be changed, added, or removed. Tuples are commonly used for storing collections of items when immutability is desired.

Characteristics of Tuples:
1. Immutable:
– Once a tuple is created, its elements cannot be modified. You cannot add, remove, or change elements in a tuple after creation.

2. Ordered:
– Like lists, tuples maintain the order of elements as they are added.
– You can access elements in a tuple using their indices.

3. Heterogeneous Elements:
– Tuples can contain elements of different data types, similar to lists.

Creating Tuples:
– Tuples are defined using parentheses `()` or the `tuple()` constructor.
– Elements within the tuple are separated by commas.

Example:
“`python
my_tuple = (1, 2, ‘hello’, True)
“`

Here are some code examples illustrating the characteristics of tuples:

1. Immutable:
“`python
# Create a tuple
my_tuple = (1, 2, 3, 4, 5)

# Attempt to modify the tuple (this will raise an error)
# Uncomment the line below to see the error
# my_tuple[0] = 10
“`

2. Ordered:
“`python
# Access elements in a tuple using indices
print(my_tuple[0]) # Output: 1
print(my_tuple[2]) # Output: 3
“`

3. Heterogeneous Elements:
“`python
# Create a tuple with elements of different data types
mixed_tuple = (1, ‘hello’, 3.14, True)

# Access elements in the mixed tuple
print(mixed_tuple[0]) # Output: 1
print(mixed_tuple[1]) # Output: ‘hello’
print(mixed_tuple[2]) # Output: 3.14
“`

Tuples are useful for representing fixed collections of items, especially when the immutability of the data is desired. They are commonly used in scenarios where the collection of items should not change over time.

 

Immutable Nature:
– Tuples cannot be modified after creation. Attempting to modify a tuple will result in an error.
– However, you can create a new tuple based on an existing tuple.

Example:
“`python
my_tuple[0] = 10 # This will raise a TypeError: ‘tuple’ object does not support item assignment
“`

Tuple Packing and Unpacking:
– Tuple packing is the process of packing multiple values into a single tuple.
– Tuple unpacking is the process of extracting values from a tuple into separate variables.

Example:
“`python
# Tuple packing
my_tuple = 1, 2, ‘hello’

# Tuple unpacking
x, y, z = my_tuple
print(x, y, z) # Output: 1 2 hello
“`

To navigate tuples in Python, you can use various techniques to access elements and perform operations on them. Here are some common syntaxes for navigating tuples:

1. Accessing Elements by Index:
“`python
my_tuple = (1, 2, 3, 4, 5)
print(my_tuple[0]) # Output: 1
print(my_tuple[3]) # Output: 4
“`

2. Slicing:
You can use slicing to retrieve a subset of elements from the tuple.
“`python
my_tuple = (1, 2, 3, 4, 5)
print(my_tuple[1:4]) # Output: (2, 3, 4)
“`

3. Negative Indexing:
Negative indexing allows you to access elements from the end of the tuple.
“`python
my_tuple = (1, 2, 3, 4, 5)
print(my_tuple[-1]) # Output: 5 (last element)
“`

4. Tuple Unpacking:
Tuple unpacking allows you to assign individual elements of the tuple to separate variables.
“`python
my_tuple = (1, 2, 3)
a, b, c = my_tuple
print(a, b, c) # Output: 1 2 3
“`

5. Iterating Through a Tuple:
You can use a loop to iterate through the elements of the tuple.
“`python
my_tuple = (1, 2, 3, 4, 5)
for item in my_tuple:
print(item)
“`

6. Tuple Concatenation:
You can concatenate tuples using the `+` operator.
“`python
tuple1 = (1, 2, 3)
tuple2 = (4, 5, 6)
combined_tuple = tuple1 + tuple2
print(combined_tuple) # Output: (1, 2, 3, 4, 5, 6)
“`

7. Once a tuple is created, no new item can be added nor removed from the tuple

Please note that you cannot directly add a new item to an existing tuple in Python. Tuples are immutable, meaning once they are created, their elements cannot be modified, added, or removed.

However, you can create a new tuple by concatenating or combining an existing tuple with other tuples or elements. Here’s how you can do it:

“`python
# Existing tuple
existing_tuple = (1, 2, 3)

# Concatenate with another tuple
new_tuple = existing_tuple + (4,)

print(new_tuple) # Output: (1, 2, 3, 4)
“`

In the example above, a new tuple `new_tuple` is created by concatenating `existing_tuple` with another tuple `(4,)`. This operation creates a new tuple with the combined elements. The original tuple `existing_tuple` remains unchanged.

 

ACCESSING THE ITEMS OF TUPLE

These are some of the common ways to navigate and work with tuples in Python, allowing you to access and manipulate data stored in tuples efficiently.

 

 
ALL AVAILABLE FUNCTIONS IN PYTHON TUPLE

To list all available functions in Python’s tuple data type, you can use the `dir()` function. This function returns a list of valid attributes and methods for the specified object. Here’s how you can do it for tuples:

“`python
# Get all available functions for tuples
tuple_functions = [func for func in dir(tuple) if not func.startswith(“__”)]

# Print the list of functions
print(tuple_functions)
“`

This code will print out a list of all available functions (methods) for tuples in Python. You can then explore these functions further in the Python documentation or through other resources.

 

SOME INBUILT FUNCTION FOR PYTHON TUPLES

Below are some built-in functions commonly used with tuples in Python:

1. `len()`:
– Returns the number of elements in the tuple.

“`python
my_tuple = (1, 2, 3, 4, 5)
print(len(my_tuple)) # Output: 5
“`

2. `count()`:
– Returns the number of occurrences of a specified value in the tuple.

“`python
my_tuple = (1, 2, 2, 3, 3, 3, 4, 4, 4, 4)
print(my_tuple.count(3)) # Output: 3
“`

3. `index()`:
– Returns the index of the first occurrence of a specified value.

“`python
my_tuple = (‘a’, ‘b’, ‘c’, ‘d’, ‘e’)
print(my_tuple.index(‘c’)) # Output: 2
“`

4. `sorted()`:
– Returns a new sorted list from the elements of the tuple.

“`python
my_tuple = (4, 2, 1, 3)
sorted_tuple = sorted(my_tuple)
print(sorted_tuple) # Output: [1, 2, 3, 4]
“`

5. `min()`:
– Returns the minimum value from the elements of the tuple.

“`python
my_tuple = (4, 2, 1, 3)
print(min(my_tuple)) # Output: 1
“`

6. `max()`:
– Returns the maximum value from the elements of the tuple.

“`python
my_tuple = (4, 2, 1, 3)
print(max(my_tuple)) # Output: 4
“`

Sure, here are a few more built-in functions commonly used with tuples in Python:

7. `any()`:
– Returns `True` if any element in the tuple is `True`. If the tuple is empty, returns `False`.

“`python
my_tuple = (False, False, True, False)
print(any(my_tuple)) # Output: True
“`

8. `all()`:
– Returns `True` if all elements in the tuple are `True`. If the tuple is empty, returns `True`.

“`python
my_tuple = (True, True, True)
print(all(my_tuple)) # Output: True
“`

9. `sum()`:
– Returns the sum of all elements in the tuple.

“`python
my_tuple = (1, 2, 3, 4, 5)
print(sum(my_tuple)) # Output: 15
“`

10. `tuple()`:
– Converts an iterable object (like a list) into a tuple.

“`python
my_list = [1, 2, 3, 4, 5]
my_tuple = tuple(my_list)
print(my_tuple) # Output: (1, 2, 3, 4, 5)
“`

11. `reversed()`:
– Returns an iterator that reverses the order of the elements in the tuple.

“`python
my_tuple = (1, 2, 3, 4, 5)
reversed_tuple = tuple(reversed(my_tuple))
print(reversed_tuple) # Output: (5, 4, 3, 2, 1)
“`

Sure, here are a few more built-in functions that can be used with tuples in Python:

12. `min()`:
– Returns the smallest element in the tuple.

“`python
my_tuple = (5, 2, 8, 3, 1)
print(min(my_tuple)) # Output: 1
“`

13. `max()`:
– Returns the largest element in the tuple.

“`python
my_tuple = (5, 2, 8, 3, 1)
print(max(my_tuple)) # Output: 8
“`

14. `len()`:
– Returns the number of elements in the tuple.

“`python
my_tuple = (5, 2, 8, 3, 1)
print(len(my_tuple)) # Output: 5
“`

15. `sorted()`:
– Returns a new sorted list from the elements of the tuple.

“`python
my_tuple = (5, 2, 8, 3, 1)
sorted_tuple = sorted(my_tuple)
print(sorted_tuple) # Output: [1, 2, 3, 5, 8]
“`

16. `enumerate()`:
– Returns an enumerate object that yields tuples containing a count (from start, which defaults to 0) and the values obtained from iterating over the given tuple.

“`python
my_tuple = (‘a’, ‘b’, ‘c’)
for index, value in enumerate(my_tuple):
print(f’Index: {index}, Value: {value}’)
“`

These built-in functions provide various capabilities for working with tuples in Python, including obtaining the length, counting occurrences, finding indices, and performing sorting operations.

 

 

USE CASES:
– Tuples are commonly used for returning multiple values from functions.
– They are also used to represent fixed collections of data, such as coordinates or dimensions.

Tuples offer a lightweight and efficient way to store and manage collections of data when immutability is desired. While they lack the mutability of lists, their immutability provides certain guarantees and safety features in your Python programs.

 

 

EXERCISES

1. Accessing Elements:
Create a tuple with some elements and then print out individual elements by accessing them using their indices.

2. Tuple Unpacking:
Define a tuple with multiple elements and then use tuple unpacking to assign each element to separate variables.

3. Concatenating Tuples:
Create two tuples and concatenate them into a single tuple. Print the resulting tuple.

4. Nested Tuples:
Construct a tuple that contains other tuples as elements. Access elements from the nested tuples.

5. Tuple Slicing:
Create a tuple with several elements and then use slicing to extract a subset of elements from the tuple.

6. Tuple Membership:
Define a tuple and then use the `in` operator to check if certain elements are present in the tuple.

7. Tuple Length:
Calculate the length of a tuple using the `len()` function.

8. Tuple Repetition:
Create a tuple with a few elements and then use the `*` operator to repeat the elements multiple times.

9. Tuple Methods:
Explore tuple methods such as `count()` and `index()`. Create a tuple with repeated elements and then use these methods to find occurrences of specific elements.

10. Immutable Nature:
Attempt to modify elements in a tuple and observe the error message that Python raises.

These exercises will help reinforce your understanding of tuples and how to work with them effectively in Python.

Join the conversation