Tuple

Tuple is like list, but we can;t modify it, they are immutable. Tuple immutable 直,就是他的直不無法修改的,有些語法是用const類似這概念。

Create Tuple 建立tuple

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
# Empty tuple
my_tuple = ()
print(my_tuple) #()

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

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

# multiply value
x,y,z, *other = (1,2,3,4,5)
print(f"x: {x}, y:{y}, z:{z}, other:{other}")
#x: 1, y:2, z:3, other:[4, 5]

my_tuple = ("mouse", [8, 4, 6], (1, 2, 3))
print(my_tuple) #('mouse', [8, 4, 6], (1, 2, 3))

created without using parentheses

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
my_tuple = 3, 4.6, "dog"
print(my_tuple)

# tuple unpacking is also possible
a, b, c = my_tuple

print(a) # 3
print(b) # 4.6
print(c) # dog

my_tuple = ("hello")
print(type(my_tuple)) # <class 'str'>

# Creating a tuple having one element
my_tuple = ("hello",)
print(type(my_tuple)) # <class 'tuple'>

# Parentheses is optional
my_tuple = "hello",
print(type(my_tuple)) # <class 'tuple'>

Access Tuple Elements

1
2
3
4
5
6
7
8
9
10
11
12
# Accessing tuple elements using indexing
my_tuple = ('p','e','r','m','i','t')

print(my_tuple[0]) # 'p'
print(my_tuple[5]) # 't'

# nested tuple
n_tuple = ("mouse", [8, 4, 6], (1, 2, 3))

# nested index
print(n_tuple[0][3]) #'s'
print(n_tuple[1][1]) # 4

# Negative indexing for accessing tuple elements

1
2
3
4
5
6
7
8
my_tuple = ('p', 'e', 'r', 'm', 'i', 't')

# Output: 't'
print(my_tuple[-1])
# elements beginning to 2nd
# Output: ('p', 'r')
print(my_tuple[:-7])

Slicing

1
2
3
4
5
6
7
8
9
10
11
12
13
14
# Accessing tuple elements using slicing
my_tuple = ('p','r','o','g','r','a','m','i','z')

# elements 2nd to 4th
# Output: ('r', 'o', 'g')
print(my_tuple[1:4])

# elements beginning to 2nd
# Output: ('p', 'r')
print(my_tuple[:-7])

#all element
#Output: ('p', 'r', 'o', 'g', 'r', 'a', 'm', 'i', 'z')
print(my_tuple[:])

change tuple

1
2
3
4
5
6
7
8
9
10
11
12
# Changing tuple values
my_tuple = (4, 2, 3, [6, 5])
my_tuple[3][0] = 9 # Output: (4, 2, 3, [9, 5])
print(my_tuple)
# Tuples can be reassigned
my_tuple = ('p', 'r', 'o', 'g', 'r', 'a', 'm', 'i', 'z')

# Concatenation
# Output: (1, 2, 3, 4, 5, 6)
print((1, 2, 3) + (4, 5, 6))
# Repeat
print(("Repeat",) * 3)

delete tuple

1
2
3
4
# Deleting tuples
my_tuple = ('p', 'r', 'o', 'g', 'r', 'a', 'm', 'i', 'z')
del my_tuple
my_tuple #NameError: name 'my_tuple' is not defined

Method

Tuple only have two method:

Method Description
count() Return the number of times a specifies value occurs in tuple
index() search the tuple for a specfied value ad returns the position of where it’s found
1
2
3
my_tuple = ('a', 'p', 'p', 'l', 'e',)
print(my_tuple.count('p')) # Output: 2
print(my_tuple.index('l')) # Output: 3

Iterating Through a Tuple

1
2
3
# Using a for loop to iterate through a tuple
for name in ('John', 'Kate'):
print("Hello", name)