Skip to content

Data Collction - Tuple 元组 (tuple) ()


Can considered Tuple is a read-only list.

Properties of list:

  • the data will not be able to make changes once defined.
  • can save many elements with different data type
  • only an exception, which is list in tuple are able to make changes.

Although tuple is read-only but a list inside of a tuple is able to make changes

py
t4 = ("Hi", "Hola", "Hello", "Whatsup", "Hello", [0, 1, 2])
print(t4)
t4[-1][1] = 1.5
print(t4)

Results:

('Hi', 'Hola', 'Hello', 'Whatsup', 'Hello', [0, 1, 2])
('Hi', 'Hola', 'Hello', 'Whatsup', 'Hello', [0, 1.5, 2])

Syntax

Define a tuple

py
variable_name = (element, element, element)

Important

  • If only define 1 item in a tuple it required to add an extra , after define element 1.

tuple.py

py
# Different with , and without it
t0 = ("Hi")
print(type(t0))

t01 = ("Hi", )
print(type(t01))
<class 'str'>
<class 'tuple'>

Define an empty tuple

py
t1 = ()
# or
t2 = tuple()

Get Item from tuple

py
tup = (123, True)
print(tup[0]) # 123

Usage

Basic Usage

tuple.py

py
# Print directly + type
t1 = (123, True, "Hello", "World")

print(t1)
print(type(t1))

# Get item
t2 = ((1, 2 ,3), (4, 5, 6))
print(t2[-1][-1]) 
# or
print(t2[1][2])

# index(), count(), len()
t3 = ("Hi", "Hola", "Hello", "Whatsup", "Hello")

print(t3.index("Hi")) # 0
print(len(t3)) # 5
print(t3.count("Hello")) # 2

Results:

(123, True, 'Hello', 'World')
<class 'tuple'>
6
6
0
5
2

Iterate tuple (while, for)

iterate-tuple.py

py
tup = (1, 2, 3, 4, 5, 6, 7, 8, 9, 10)
odd_list = list()
even_list = list()

# find odd - while
index = int(0)

while index < len(tup):

    if tup[index] % 2 != 0:
        odd_list.append(tup[index])

    index += 1

# find even - for
for item in tup:

    if item % 2 == 0:
        even_list.append(item)

print(f"Odd: {odd_list}")
print(f"Even: {even_list}")

Results:

Odd: [1, 3, 5, 7, 9]
Even: [2, 4, 6, 8, 10]