# Tuples in Python

This article delves into the realm of [Python](https://realpython.com/python-namedtuple/) [tuples](https://www.geeksforgeeks.org/tuples-in-python/), concentrating on their intricacies, syntax, and significance in programming. It seeks to enrich the understanding and abilities of both experienced programmers and beginners, emphasizing the fundamental principles of code modularity and the crucial role functions play in [Python](https://www.crio.do/blog/python-projects-for-beginners/?utm_source=adwords&utm_medium=Blog&utm_campaign=Python-Beginner-Blog&utm_term=python%20for%20beginners&gad=1&gclid=CjwKCAjwgZCoBhBnEiwAz35Rwt2__8fpn2B8O60kBkiem_5XruyfkhwL-v_VEQD2xdyv7oZW_eZcFxoCvH8QAvD_BwE) development

* **What is** [**Tuples**](https://www.w3schools.com/python/python_tuples.asp)**?**
    
* **Creating** [**Tuples**](https://www.programiz.com/python-programming/tuple)
    
* **Accessing the** [**Tuple**](https://medium.com/geekculture/all-you-need-to-know-about-tuples-in-python-8e382c93ce8c) **Elements**
    
* **Basic Operations on** [**Tuples**](https://www.javatpoint.com/python-tuples)
    
* **Nested** [**Tuples**](https://www.tutorialspoint.com/python/python_tuples.htm)
    
* **Immutable** [**Tuples**](https://www.dataquest.io/blog/python-tuples/)
    

## **What is** [Tuples](https://www.scaler.com/topics/python/tuples-in-python/)?

*"A* [*tuple*](https://www.edureka.co/blog/tuple-in-python/) *is an ordered, immutable, and finite collection of elements in* [*Python*](https://ladderpython.com/lesson/tuple-functions-in-python-tuple-methods-in-python/)*. It is similar to a list in that it can store multiple items, but unlike lists, once a* [*tuple*](https://problemsolvingwithpython.com/04-Data-Types-and-Variables/04.05-Dictionaries-and-Tuples/) *is created, its elements cannot be modified, added, or removed.* [*Tuples*](https://pynative.com/python-tuples/) *are typically enclosed within parentheses* `()`*."*

### [Tuple](https://www.softwaretestinghelp.com/python/python-tuple/) properties

* **Ordered:** [Tuples](https://realpython.com/python-lists-tuples/) maintain a specific order of elements, accessible by their indices, which remain consistent throughout their existence.
    
* **Immutable:** [Tuples](https://intellipaat.com/blog/tutorial/python-tutorial/python-tuple/) are unchangeable once created, making them suitable for storing constant data in situations where modifications should not occur.
    
* **Heterogeneous:** [Tuples](https://365datascience.com/tutorials/python-tutorials/tuples-python/) offer flexibility in storing a mix of data types, allowing them to contain elements of numbers, strings, and other [tuples](https://brainstation.io/learn/python/tuple).
    
* **Fixed Size:** [Tuples](https://www.toppr.com/guides/python-guide/references/methods-and-functions/methods/built-in/tuple/creating-tuple-python/) have a fixed size, determined at creation, and cannot be changed. To add or remove elements, a new [tuple](https://www.codingem.com/what-is-a-tuple-in-python/) must be created.
    
* **Iterable:** [Tuples](https://www.digitalocean.com/community/tutorials/understanding-tuples-in-python-3) can be iterated over using loops, enabling sequential processing of each element within the [tuple](https://pythongeeks.org/python-tuples/).
    
* **Supports Slicing:** Slicing [tuples](https://docs.python.org/3/c-api/tuple.html) allows for the extraction of specific data portions by creating new [tuples](https://www.atatus.com/blog/python-tuples/) containing a subset of the original elements.
    
* **Hashable:** [Tuples](https://www.datacamp.com/tutorial/python-tuples-tutorial) are hashable, allowing them to be used as keys in dictionaries and elements in sets due to their immutability and constant hash value.
    
* **Memory Efficiency:** [Tuples](https://builtin.com/software-engineering-perspectives/python-tuples-vs-lists) are more memory-efficient due to their fixed size, while lists may require additional memory for growth.
    

### **Creating** [**Tuples**](https://beginnersbook.com/2018/02/python-tuple/)

*" Simply enclose a sequence of elements within parentheses* `()` *to create a* [*tuple*](https://www.learnbyexample.org/python-tuple/)*."*

```python
my_tuple = (1, 2, 3, 4, 5)
```

### Accessing [Tuple](https://datatrained.com/post/tuple-in-python/) Elements

*"Use indexing to access specific members of a* [*tuple*](https://www.quackit.com/python/tutorial/python_tuples.cfm)*.* [*Python*](https://www.scaler.com/topics/reduce-function-in-python/) *indexing begins at* ***0.****"*

```python
# Create a tuple
my_tuple = (10, 20, 30, 40, 50)

# Access elements using indexing
first_element = my_tuple[0]   # Access the first element (index 0)
second_element = my_tuple[1]  # Access the second element (index 1)
third_element = my_tuple[2]   # Access the third element (index 2)
fourth_element = my_tuple[3]  # Access the fourth element (index 3)
fifth_element = my_tuple[4]   # Access the fifth element (index 4)

# Print the accessed elements
print("First Element:", first_element) # output 10
print("Second Element:", second_element) # output 20
print("Third Element:", third_element) # output 30
print("Fourth Element:", fourth_element) # output 40
print("Fifth Element:", fifth_element) # output 50
```

## Basic Operations on Tuples

### Concatenate using `+`

*"Using the* ***'+'*** *operator, you can concatenate two* [*tuples*](https://www.w3resource.com/python-exercises/tuple/)*."*

```python
# Create two tuples
tuple1 = (1, 2, 3)
tuple2 = (4, 5, 6)

# Concatenate the two tuples
concatenated_tuple = tuple1 + tuple2

# Print the concatenated tuple
print("Concatenated Tuple:", concatenated_tuple)
# Concatenated Tuple: (1, 2, 3, 4, 5, 6)
```

### Repeat using `*`

*"Using the '****\*'*** *operator, you may generate a new* [*tuple*](https://www.learnpython.dev/02-introduction-to-python/080-advanced-datatypes/30-tuples/) *by repeating an existing* [*tuple*](https://howtodoinjava.com/python-datatypes/python-tuples/)*."*

```python
original_tuple = (1, 2)
new_tuple = original_tuple * 3
# Resulting tuple: (1, 2, 1, 2, 1, 2)
```

### Check membership using `in`

*"To determine whether an element is in a* [*tuple*](https://pythonnumericalmethods.berkeley.edu/notebooks/chapter02.04-Data-Structure-Tuples.html)*, use the '****in****' operator."*

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

# Check if an element is in the tuple
if 3 in my_tuple:
    print("3 is in the tuple")
else:
    print("3 is not in the tuple")

# Check if a different element is in the tuple
if 6 in my_tuple:
    print("6 is in the tuple")
else:
    print("6 is not in the tuple")
#Output
# 3 is in the tuple
# 6 is not in the tuple
```

### Find length using `len()`

*"The* ***'len()'*** *method returns the length of a* [*tuple.*](https://data-flair.training/blogs/python-tuple/)*"*

```python
# Create a tuple
my_tuple = (10, 20, 30, 40, 50)

# Find the length of the tuple
length_of_tuple = len(my_tuple)

# Print the length
print("Length of the tuple:", length_of_tuple)
# output
# Length of the tuple: 5
```

The [tuple](https://studyglance.in/python/tuple.php) `my_tuple` is created with five elements, its length is calculated using the `len()` function and the length is stored in the variable `length_of_tuple`.

### Nested [Tuples](https://www.w3schools.com/python/ref_func_tuple.asp)

*"*[*Tuples*](https://www.w3schools.com/python/python_tuples_update.asp) *can be nested, meaning you can have* [*tuples*](https://www.jcchouinard.com/python-tuples/) *inside other* [*tuples*](https://www.tutorialsteacher.com/python/python-tuple)*"*

* Nested [tuples](https://www.linode.com/docs/guides/python-tuples/) are [tuples](https://www.knowledgehut.com/tutorials/python-tutorial/python-lists-tuples) that are enclosed within other [tuples](https://blog.hubspot.com/website/python-tuple).
    
* You may express and organize complicated data hierarchies using layered structures.
    
* You may use custom functions to browse and manipulate data within nested [tuples](https://www.educba.com/tuples-in-python/) by traversing the layers of nesting recursively.
    
* **Recursion:**
    

Recursion is a programming technique used to solve smaller subproblems in nested [tuples](https://www.freecodecamp.org/news/python-tuple-vs-list-what-is-the-difference/), where a function calls itself to navigate through the nesting layers.

* **Base Case:**
    

To effectively implement recursion, define a base case that specifies when the recursion should stop, often involving handling unnested [tuples](https://www.youtube.com/watch?v=zLFituJxj6c&ab_channel=Jenny%27sLecturesCSIT) in nested [tuples](https://www.studytonight.com/python/tuples-in-python).

### **Accessing Elements in Nested** [**Tuples**](https://www.python-engineer.com/courses/advancedpython/02-tuples/)

Function to access an element in a nested [tuple](https://www.w3schools.com/python/python_tuples_access.asp) by providing a list of indices

```python
def access_nested_tuple(nested_tuple, indices):
    if not indices:
        return nested_tuple
    else:
        index = indices[0]
        rest_of_indices = indices[1:]
        return access_nested_tuple(nested_tuple[index], rest_of_indices)

# Nested tuple
nested_tuple = ((1, 2), (3, (4, 5)), 6)

# Access elements using the function
element = access_nested_tuple(nested_tuple, [1, 1, 0])  # Accessing 4

print("Element:", element)
```

The **<mark>access_nested_tuple</mark>** function uses recursion to access an element within a nested [tuple](https://www.w3schools.com/python/python_ref_tuple.asp), like element 4, by providing indices \[1, 1, 0\].

## Immutable [Tuples](https://www.pythontutorial.net/python-basics/python-tuples/)

[Tuples](https://dotnettutorials.net/lesson/tuples-in-python/) are immutable, which implies that their elements cannot be introduced, updated, or removed after they are created. Similar effects can be achieved by constructing new [tuples](https://thenewstack.io/python-for-beginners-when-and-how-to-use-tuples/) with the required adjustments. You can insert, alter, and delete elements in [tuples](https://python.plainenglish.io/python-tuple-tuple-functions-and-tuple-operations-in-python-bd7d9d9940be) in the following ways:

* **Creating a New** [**Tuple**](https://www.w3schools.com/python/python_tuples_loop.asp)**:** To add elements to an existing tuple, you need to create a new [tuple](https://www.w3schools.com/python/gloss_python_tuple_one_item.asp) that includes the elements from the original [tuple](https://www.w3schools.com/python/python_tuples_exercises.asp) along with the new elements. You cannot modify the original [tuple](https://www.w3schools.com/python/gloss_python_change_tuple_item.asp) in place.
    
* **Concatenation:** One way to add elements is by concatenating two or more [tuples](https://www.section.io/engineering-education/tuples-data-structure-python/) using the `+` operator or creating a new [tuple](https://www.w3schools.com/python/gloss_python_access_tuple_items.asp) by including elements from both the original [tuple](https://www.w3schools.com/python/gloss_python_tuple_length.asp) and new elements.
    
* **Reassignment:** After creating a new [tuple](https://www.w3schools.com/python/ref_tuple_count.asp) with the desired elements, you can reassign it to the variable containing the original [tuple](https://www.w3schools.com/python/gloss_python_loop_tuple_items.asp) to effectively "**update**" the [tuple](https://www.w3schools.com/python/python_tuples_unpack.asp).
    

### **Inserting Elements in a** [**Tuple**](https://www.w3schools.blog/python-tuples)

*"To insert items into a* [*tuple*](https://www.w3schools.in/python/tuples)*, you must first build a new* [*tuple*](http://www.w3schools-fa.ir/python/python_tuples.html) *that contains both the current and new elements. To do this, utilize* [*tuple*](https://www.geeksforgeeks.org/tuples-in-python/) *concatenation."*

```python
# Original tuple
original_tuple = (1, 2, 3)
# Creating a New Tuple
new_elements = (4, 5)
# Concatenation
updated_tuple = original_tuple + new_elements
# Reassignment
original_tuple = updated_tuple
print("Updated Tuple:", original_tuple)
# Output updated tuple
# Updated Tuple: (1, 2, 3, 4, 5)
```

The code creates an original [tuple](https://www.w3resource.com/python-exercises/tuple/), adds elements **(4, 5)** to it, creates a new [tuple](https://www.javatpoint.com/python-tuples) **(updated\_tuple)**, concatenates them, reassigns the updated [tuple](https://www.toppr.com/guides/computer-science/programming-with-python/tuples/tuple-assignment/) to the original [tuple](https://www.linkedin.com/posts/talaal-yousoof-74bb44253_tuples-python-pythonprogramming-activity-7092560117325295616-yfAI), and prints it.

### **Modifying Elements of a** [**Tuple**](https://www.tutorialspoint.com/How-to-convert-a-list-into-a-tuple-in-Python)

*"To modify an element in a* [*tuple*](https://www.programiz.com/python-programming/tuple)*, create a new* [*tuple*](https://favtutor.com/blogs/list-to-tuple-python) *with desired modifications using slicing, keeping elements before and after the modified one unchanged."*

```python
original_tuple = (1, 2, 3, 4, 5)

# creating a new tuple
index_to_modify = 2  # Index of the element to modify
new_value = 10  # New value for the element

#  modification
updated_tuple = original_tuple[:index_to_modify] + (new_value,) + original_tuple[index_to_modify + 1:]

# Reassignment
original_tuple = updated_tuple

# Print the updated tuple
print("Updated Tuple:", original_tuple)
```

Original [tuple](https://www.freecodecamp.org/news/python-namedtuple-examples-how-to-create-and-work-with-namedtuples/) `original_tuple` with elements 1, 2, 3, 4, 5) and modifies an element at index 2 by assigning a new value. A new [tuple](https://sparkbyexamples.com/python/convert-list-to-tuple-in-python/) `updated_tuple` is created by slicing the original [tuple](https://www.tutorialsteacher.com/csharp/csharp-tuple) into three parts, concatenating them, and reassigning them to the original variable.

### **Deleting Elements from a** [**Tuple**](https://www.upgrad.com/blog/list-vs-tuple/)

*"To remove an element from a* [*tuple*](https://byjus.com/gate/difference-between-list-tuple-set-and-dictionary-in-python/)*, create a new* [*tuple*](https://docs.python.org/3/library/itertools.html) *that excludes the desired element, and use slicing to skip the desired element."*

```python
# Original tuple
original_tuple = (1, 2, 3, 4, 5)

# Index of the element to delete
index_to_delete = 2

# Create a new tuple 
updated_tuple = original_tuple[:index_to_delete] + original_tuple[index_to_delete + 1:]

print("Updated Tuple:", updated_tuple)
# Output
# Updated Tuple: (1, 2, 4, 5)
```

<details data-node-type="hn-details-summary"><summary>Summary</summary><div data-type="detailsContent"><a target="_blank" rel="noopener noreferrer nofollow" href="https://www.codingninjas.com/studio/library/introduction-to-python-tuples" style="pointer-events: none">Tuples</a> in <a target="_blank" rel="noopener noreferrer nofollow" href="https://www.guru99.com/python-counter-collections-example.html" style="pointer-events: none">Python </a>are created by enclosing elements within parentheses, accessible using indexing, and supporting basic operations like concatenation, repetition, membership checks, and length. They can be nested for more complex data structures. <a target="_blank" rel="noopener noreferrer nofollow" href="https://www.makeuseof.com/how-to-create-and-use-tuples-in-python/" style="pointer-events: none">Tuples</a> are immutable, to insert, modify, or delete elements, create new <a target="_blank" rel="noopener noreferrer nofollow" href="https://www.pylenin.com/blogs/python-tuples/" style="pointer-events: none">tuples</a> with the desired changes and reassign them to the original <a target="_blank" rel="noopener noreferrer nofollow" href="https://stackoverflow.com/questions/2970608/what-are-named-tuples-in-python" style="pointer-events: none">tuple </a>variable.</div></details><div data-node-type="callout">
<div data-node-type="callout-emoji">💡</div>
<div data-node-type="callout-text"><a target="_blank" rel="noopener noreferrer nofollow" href="https://www.simplilearn.com/tutorials/python-tutorial/python-interview-questions" style="pointer-events: none">Python</a> <a target="_blank" rel="noopener noreferrer nofollow" href="https://python-reference.readthedocs.io/en/latest/docs/tuple/" style="pointer-events: none">tuples</a> are a vital data structure that provides several benefits such as memory efficiency, immutability, and the ability to hold diverse data. They are especially effective when constant data must be saved and secured against alteration. While its immutability might be a limitation, developers can get around it by constructing new <a target="_blank" rel="noopener noreferrer nofollow" href="https://sparkbyexamples.com/python/python-tuple-explain/" style="pointer-events: none">tuples</a> with the appropriate modifications. Understanding and mastering <a target="_blank" rel="noopener noreferrer nofollow" href="https://thomas-cokelaer.info/tutorials/python/tuples.html" style="pointer-events: none">tuples</a> can help you improve your programming skills and expand your understanding of <a target="_blank" rel="noopener noreferrer nofollow" href="https://jovian.com/jahagirmay/lists-tuples-and-dictionaries-in-python" style="pointer-events: none">Python</a>'s possibilities.</div>
</div>
