Python Datatype - Part 3 (Tuples)

Python Datatype - Part 3 (Tuples)

Python Tuples

As we learnt in the last class there are datatype use to store multiple items in single variable. Python have 4 built-in data type that stores collections of data, they are Tuples, List, Set and Dictionary.

Tuples are written with round brackets.

mytuple = ("Red", "Orange", "Green", "Black")
print(mytuple)        

  • Tuple items are ordered, unchangeable, and allow duplicate values.
  • Tuple items are indexed, the first item has index [0], the second item has index [1] etc.
  • Tuple items can be of any data type

tuple1 = ("apple", "banana", "cherry")

tuple2 = (1, 5, 7, 9, 3)

tuple3 = (True, False, False)        

A tuple can contain different data types

tuple1 = ("abc", 34, True, 40, "male")        

  • Ordered: When we say that tuples are ordered, it means that the items have a defined order, and that order will not change.
  • Unchangeable: Tuples are unchangeable, meaning that we cannot change, add or remove items after the tuple has been created.
  • Allow Duplicates: Since tuples are indexed, they can have items with the same value.

Example: Tuples allow duplicate values:

mytuple = ("Red", "Orange", "Green", "Black", "Green", "Red")

print(mytuple)        

Tuple len()

len() method is use to determine the number of items in a tuple

mytuple = ("Red", "Orange", "Green", "Black")

print(len(mytuple))        

Tuple items can be of any data type:

tuple1 = ("apple", "banana", "cherry")

tuple2 = (1, 5, 7, 9, 3)

tuple3 = (True, False, False)        

Access Tuple Items

To access the tuple items, you will need to use the index number to reference them.

Note: The first item has index 0.

mytuple = ("Red", "Orange", "Green", "Black")

print(mytuple[1])        

Negative Indexing

Negative indexing means starting the index check from the end. -1 refers to the last item, -2 refers to the second last item etc.

mytuple = ("Red", "Orange", "Green", "Black")

print(mytuple[-1])        

Range of Indexes

You can specify a range of indexes by specifying where to start and where to end the range.

thistuple = ("apple", "banana", "cherry", "orange", "kiwi", "melon", "mango")

print(thistuple[2:5])        

Note: The search will start at index 2 (included) and end at index 5 (not included).

To start at the first item leave out the start value:

thistuple = ("apple", "banana", "cherry", "orange", "kiwi", "melon", "mango")

print(thistuple[:5])        

To go to the end item leave out the end value

thistuple = ("apple", "banana", "cherry", "orange", "kiwi", "melon", "mango")

print(thistuple[4:])        

Range of Negative Indexes

Negative index is use to start the search from the end of the list

mytuple = ("Red", "Orange", "Green", "Black", "Blue", "Yellow", "Brown", "White")

print(mytuple[-4:-1])        

Check if Item Exists

To determine if a specified item is present in a tuple use the "in" keyword:

mytuple = ("Red", "Orange", "Green", "Black", "Blue", "Yellow", "Brown", "White")

if "Blue" in mytuple:
  print("Yes, 'Blue' is in the color tuple")
else:
  print("Yes, 'Blue' is not in the color list")        

Change Tuple Value

Once a tuple is created, you cannot change its values. Tuples are unchangeable.

The workaround, you can convert the tuple into a list, change the list, and convert the list back into a tuple.

mytuple = ("Red", "Orange", "Green")

y = list(mytuple)
y[1] = "Blue"

newtuple = tuple(y)
print(newtuple)        

Add Items

Tuple have no built-in append() method, but converting to list as above will allow to add items to a tuple.

thistuple = ("Red", "Orange", "Green")

y = list(thistuple)
y.append("Black")

thistuple = tuple(y)
print(thistuple)        

Add tuple to a tuple

thistuple = ("Red", "Orange", "Green")

newtuple = ("Black", "Brown")
thistuple += newtuple

print(thistuple)        

Remove Items

To remove item you can already guess one have to convert to list, remove item and convert back to tuple.

thistuple = ("Red", "Brown", "Orange", "Green")

y = list(thistuple)
y.remove("Brown")

thistuple = tuple(y)
print(thistuple)        

Unpack Tuples

Is extracting the values of a tuple items back into variables

Example:

colors = ("Red", "Brown", "Orange", "Green")

(red, brown, orange, green) = colors

print(red)
print(brown)
print(orange)
print(green)        

Using Asterisk*

* can be use to assign a list to one of the variable if number of values is more than the variables

colors = ("Red", "Brown", "Orange", "Green", "Black")

(red, brown, *others) = colors

print(red)
print(brown)
print(others)        

If the asterisk is added to another variable name than the last, Python will assign values to the variable until the number of values left matches the number of variables left.

colors = ("Red", "Brown", "Orange", "Green", "Black")

(red, *others, black) = colors

print(red)
print(others)
print(black)        

Loop Through a Tuple

Using For loop

thistuple = ("Red", "Brown", "Orange", "Green", "Black")

for x in thistuple:
  print(x)        

Loop Through the Index Numbers: Use the range() and len() functions to create a suitable iterable.

thistuple = ("Red", "Brown", "Orange", "Green", "Black")

for i in range(len(thistuple)):
  print(thistuple[i])        

While Loop: Use the len() function to determine the length of the list

thistuple = ("Red", "Brown", "Orange", "Green", "Black")

i = 0
while i < len(thistuple):
  print(thistuple[i])
  i = i + 1        

Join Tuples

We have taken a look at this earlier while learning  adding tuple to another tuple. The concept is the same you use a + to join tuples together.

tuple1 = ("Red", "Brown", "Orange", "Green", "Black")
tuple2 = (1, 2, 3)
tuple3 = (6.4, 13.0, 16.1, 10.4)
tuple4 = tuple1 + tuple2 + tuple3

print(tuple4)        

Tuple Methods

count(): Returns the number of times a specified value occurs in a tuple

index(): Searches the tuple for a specified value and returns the position of where it was found

To view or add a comment, sign in

More articles by Abdulmutalib Idris

  • Improving Nigerian Education Through School Management Systems

    The Nigerian education sector faces numerous challenges, particularly at the higher institution level. These include…

  • Python Lambda

    Is a function that take as many arguments as possible but can only have one expression. They are also consider…

  • Python Functions

    A function is a block of code which only runs when it is called. You can pass data, known as parameters, into a…

    2 Comments
  • Python Conditional and Loop Statements

    If ..

    1 Comment
  • Python Datatype - Part 5 (Dictionary)

    As we learnt earlier Dictionary is one of 4 built-in data types in Python used to store collections of data, the other…

    2 Comments
  • Python Datatype - Part 4 (Sets)

    Python Sets As we learnt earlier Set is one of 4 built-in data types in Python used to store collections of data, the…

    1 Comment
  • Python Datatype - Part 2 (Lists)

    Python Lists There are datatype use to store multiple items in single variable. Python have 4 built-in datatype that…

    1 Comment
  • Python Datatype - Part 1

    In the last class we talked about variables and we said variable data type is whatever values are assigned to the…

  • Python Variables

    In python variables are the reserved memory locations used for storing values. In python a built-in id() function…

  • Python Indentation, Multi-line Statements, and Quotations

    Python Indentation The spaces left at the beginning of a code line is called indentation. In other languages indenting…

    1 Comment

Explore content categories