Python Tuples

Python Tuples

A tuple in Python is an immutable, ordered sequence of elements. Once created, the elements within a tuple cannot be changed. Tuples are commonly used when a collection of data needs to be stored, but you don’t want it to be modified. Tuples are determined by circular brackets ( )

Example:

# Examples of tuple in Python
tuple1 = () # An empty tuple
tuple2 = (4, 5, 1, 7, 3) # A tuple with 5 integers
tuple3 = (True, False, True, False, True) # A tuple with 5 boolean values
tuple4 = (1, ‘XYZ’, True) # In Python, different types of values can be stored in a tuple

Explanation:
● tuple1 = ( ): This is an empty tuple that doesn’t contain any elements.
● tuple2 = (4, 5, 1, 7, 3): This tuple contains 5 integer values: 4, 5, 1, 7, and 3.
● tuple3 = (True, False, True, False, True): This tuple contains 5 boolean values: True, False, True, False, and True.
● tuple4 = (1, ‘XYZ, ‘True’): This tuple contains 3 values of distinct data types. In python it is possible to store different types of values.

Creating and Accessing a Python tuple:
Scenario: Let’s create a tuple with the values {2, 4, 10, 5, 15, 3} and access the 3rd element using the tuple index.

# Create a tuple and access the 3rd element
numbers = (2, 4, 10, 5, 15, 3)
print(f”The third element: {numbers[2]}”)

Explanation:
● numbers = (2, 4, 10, 5, 15, 3): This initializes a tuple with 6 integer values: 2, 4, 10, 5, 15, and 3.
● print(f”The third element: {numbers[2]}”): This prints the 3rd element of the tuple. In Python, tuples are zero-indexed, meaning the index starts from 0. Therefore, numbers[2] refers to the 3rd element, which is 10.

Course Video

Course Video English:

Task

1. Integer tuple:
Create a tuple of integers with values from 1 to 5.
Print all elements of the tuple.

2. String tuple:
Create a tuple of strings with the names of three fruits.
Print all elements of the tuple.

3. Double tuple:
Create a tuple of doubles with any 4 double values.
Print the sum of all elements in the tuple.

4. Boolean tuple:
Create a tuple of booleans with alternating true and false values.
Print all elements of the tuple.

Task Video

YouTube Reference :

Frequently Asked Questions

Still have a question?

Let's talk

Tuples in Python are immutable, ordered collections.

Functions of a tuple: count(), index(), len(), min(), max().

Tuples are used for immutable data storage.

Tuples are created using parentheses ().

Lists are mutable; tuples are immutable.

List methods include append(), remove(), pop(), etc.

Tuples in Python are immutable, ordered collections.

Tuples are ordered and immutable collections.

Tuples offer better performance and data safety.

Tuples store immutable data, unlike lists.

Chatbot