DEV Community

Cover image for Python Tuples
Christopher Ambala
Christopher Ambala

Posted on • Edited on

Python Tuples

It's been a while since my last post😐,But I'm back with interesting python topics as I learn😃
Today we look at core python data types which are;

  • Tuples
  • Int
  • Lists
  • Dictionaries
  • Numbers
  • sets
  • File

Tuples

Tuples are ordered collections of heterogeneous data that are unchangeable.
They have the following characteristics;

tuples

  • Ordered: Tuples are part of sequence data types, which means they hold the order of the data insertion. It maintains the index value for each item.
  • Unchangeable: Tuples are unchangeable, which means that we cannot add or delete items to the tuple after creation.
  • Heterogeneous: Tuples are a sequence of data of different data types (like integer, float, list, string, etc;) and can be accessed through indexing and slicing.
  • Contains Duplicates: Tuples can contain duplicates, which means they can have items with the same value.

Creating tuples
They are created using () or the built in function tuple ()

# Using empty parentheses
mytuple = ()
Enter fullscreen mode Exit fullscreen mode
# Using tuple() function
mytuple = tuple()
Enter fullscreen mode Exit fullscreen mode

Creating a tuple with elements.

A tuple is created by placing all the items (elements) inside parentheses, separated by commas. The parentheses are optional, however, it is a good practice to use them.

A tuple can have any number of items and they may be of different types (integer, float, list, string, etc.).

# Different types of tuples
# Empty tuple
my_tuple = ()
print(my_tuple)

# Tuple having integers
my_tuple = (1, 2, 3)
print(my_tuple)

# tuple with mixed datatypes
my_tuple = (1, "Hello", 3.4)
print(my_tuple)

# nested tuple
my_tuple = ("mouse", [8, 4, 6], (1, 2, 3))
print(my_tuple)
Enter fullscreen mode Exit fullscreen mode

Output

()
(1, 2, 3)
(1, 'Hello', 3.4)
('mouse', [8, 4, 6], (1, 2, 3))
Enter fullscreen mode Exit fullscreen mode

Using the tuple() constructor.

tuple([iterable])
Enter fullscreen mode Exit fullscreen mode

Tuple packing and unpacking:

Packing: Packing is the process of putting values into a tuple. You can create a tuple by separating values with commas, and Python will automatically pack them into a tuple.

# Packing
my_tuple = 1, 2, 'three', 4.0
print(my_tuple)  # Output: (1, 2, 'three', 4.0)
Enter fullscreen mode Exit fullscreen mode

Unpacking: Unpacking is the process of extracting values from a tuple. You can assign the elements of a tuple to multiple variables in a single line.

# Unpacking
a, b, c, d = my_tuple
print(a)  # Output: 1
print(b)  # Output: 2
print(c)  # Output: 'three'
print(d)  # Output: 4.0
Enter fullscreen mode Exit fullscreen mode

Accessing tuples by index.

To access an item through its index, you can use the following syntax:

tuple_object[index]
Enter fullscreen mode Exit fullscreen mode
# Creating a tuple
my_tuple = (1, 2, 'three', 4.0)

# Accessing elements using indexing
first_element = my_tuple[0]
second_element = my_tuple[1]
third_element = my_tuple[2]
fourth_element = my_tuple[3]

# Printing the elements
print("First element:", first_element)   # Output: 1
print("Second element:", second_element)  # Output: 2
print("Third element:", third_element)    # Output: 'three'
print("Fourth element:", fourth_element)  # Output: 4.0
Enter fullscreen mode Exit fullscreen mode

using a negative index;

# Accessing elements using negative indexing
last_element = my_tuple[-1]    # Equivalent to my_tuple[3]
second_last = my_tuple[-2]     # Equivalent to my_tuple[2]

# Printing the elements
print("Last element:", last_element)       # Output: 4.0
print("Second last element:", second_last)  # Output: 'three'
Enter fullscreen mode Exit fullscreen mode

Retrieving Multiple elements in tuples.

tuple_object[start:stop:step]
Enter fullscreen mode Exit fullscreen mode
  • start: The index where the slice begins.
  • stop: The index where the slice ends (exclusive).
  • step: The step or stride between elements.
my_tuple = (1, 2, 3, 4, 5, 6, 7, 8, 9, 10)

# Slicing from index 2 to index 7 (exclusive) with a step of 2
sliced_tuple = my_tuple[2:7:2]

print(sliced_tuple)
Enter fullscreen mode Exit fullscreen mode
#Output

(3, 5, 7)
Enter fullscreen mode Exit fullscreen mode

What happens if you index out of range.

If you use an index greater than or equal to the tuple’s length, then you get an IndexError exception:

my_tuple = (1, 2, 'three', 4.0)
print(my_tuple[5])


Traceback (most recent call last):
    ...
IndexError: tuple index out of range
Enter fullscreen mode Exit fullscreen mode

Accessing elements within a nested tuple.

Accessing elements within nested tuples involves using multiple levels of indexing. Each level of nesting requires an additional set of square brackets to access the desired element.

# Creating a nested tuple
nested_tuple = (1, 2, (3, 4), ('five', 6))

# Accessing elements in the nested tuple
first_element = nested_tuple[0]
third_element_nested = nested_tuple[2]
first_element_nested = nested_tuple[2][0]
second_element_nested = nested_tuple[3][1]

# Printing the accessed elements
print("First element:", first_element)                 
 # Output: 1

print("Third element (nested tuple):", third_element_nested) 
 # Output: (3, 4)

print("First element of the nested tuple:", first_element_nested) 
 # Output: 3

print("Second element of the nested tuple:", second_element_nested) 
 # Output: 6
Enter fullscreen mode Exit fullscreen mode

Tuple concatenation

You can concatenate two tuples in Python using the + operator. The result will be a new tuple that contains the elements of both original tuples.

pythonCopy code

# Two tuples to be concatenated
tuple1 = (1, 2, 3)
tuple2 = ('four', 'five', 'six')

# Concatenating the two tuples
concatenated_tuple = tuple1 + tuple2

# Printing the concatenated tuple
print("Concatenated Tuple:", concatenated_tuple)
Enter fullscreen mode Exit fullscreen mode
#Output

Concatenated Tuple: (1, 2, 3, 'four', 'five', 'six')
Enter fullscreen mode Exit fullscreen mode

Compare two tuples

In Python, you can compare two tuples using the comparison operators (==, !=, <, >, <=, >=). The comparison is performed element-wise, starting from the first element, and stops as soon as a decisive result is reached.

tuple1 = (1, 2, 3)
tuple2 = (1, 2, 4)

# Equality check
print("tuple1 == tuple2:", tuple1 == tuple2)  # Output: False


# Inequality check
print("tuple1 != tuple2:", tuple1 != tuple2)  # Output: True


# Less than check
print("tuple1 < tuple2:", tuple1 < tuple2)    # Output: True

# Greater than check
print("tuple1 > tuple2:", tuple1 > tuple2)    # Output: False


# Less than or equal to check
print("tuple1 <= tuple2:", tuple1 <= tuple2)  # Output: True


# Greater than or equal to check
print("tuple1 >= tuple2:", tuple1 >= tuple2)  # Output: False
Enter fullscreen mode Exit fullscreen mode

Using tuple packing and unpacking to return multiple values from a function

Tuple packing and unpacking in Python can be used to return multiple values from a function. This is a convenient way to bundle multiple values together and then easily unpack them when needed.

def get_coordinates():
    x = 10
    y = 20
    z = 30
    # Tuple packing
    return x, y, z


# Function call
result = get_coordinates()

# Result is a tuple
print(result)  


# Output: (10, 20, 30)
Enter fullscreen mode Exit fullscreen mode

Tuple Unpacking: When calling the function, you can unpack the returned tuple into individual variables:

def get_coordinates():
    x = 10
    y = 20
    z = 30
    return x, y, z

# Tuple unpacking
x_result, y_result, z_result = get_coordinates()

# Individual values
print("X:", x_result)  

# Output: 10

print("Y:", y_result) 

 # Output: 20

print("Z:", z_result) 

 # Output: 30
Enter fullscreen mode Exit fullscreen mode

This is just a brief introduction into Tuples For further reading this Python Documentation will be in depth of what I have covered.

Top comments (0)