Bài trước: Python căn bản (16): Python Lists (cont.3)
[Từ điển]
17. Python Tuples
17.1 Tuple
Tuples are used to store multiple items in a single variable.
Tuple is one of 4 built-in data types in Python used to store collections of data, the other 3 are List, Set, and Dictionary, all with different qualities and usage.
A tuple is a collection which is ordered and unchangeable.
Tuples are written with round brackets.
Example
Create a Tuple:
thistuple = ("apple", "banana", "cherry")
print(thistuple)
Tuple Items
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.
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:
thistuple = ("apple", "banana", "cherry", "apple", "cherry")
print(thistuple)
Tuple Length
To determine how many items a tuple has, use the len() function.
Example
Print the number of items in the tuple:
thistuple = ("apple", "banana", "cherry")
print(len(thistuple))
Create Tuple With One Item
To create a tuple with only one item, you have to add a comma after the item, otherwise Python will not recognize it as a tuple.
Example
One item tuple, remember the comma:
thistuple = ("apple",)
print(type(thistuple))
#NOT a tuple
thistuple = ("apple")
print(type(thistuple))
Tuple Items - Data Types
Tuple items can be of any data type.
Example
String, int and boolean data types:
tuple1 = ("apple", "banana", "cherry")
tuple2 = (1, 5, 7, 9, 3)
tuple3 = (True, False, False)
A tuple can contain different data types.
Example
A tuple with strings, integers and boolean values:
tuple1 = ("abc", 34, True, 40, "male")
type()
From Python's perspective, tuples are defined as objects with the data type 'tuple'.
<class 'tuple'>
Example
What is the data type of a tuple?
mytuple = ("apple", "banana", "cherry")
print(type(mytuple))
The tuple() Constructor
It is also possible to use the tuple() constructor to make a tuple.
Example
Using the tuple() method to make a tuple:
thistuple = tuple(("apple", "banana", "cherry")) # note the double round-brackets
print(thistuple)
17.2 Access Tuple Items
You can access tuple items by referring to the index number, inside square brackets.
Example
Print the second item in the tuple:
thistuple = ("apple", "banana", "cherry")
print(thistuple[1])
Note: The first item has index 0.
Negative Indexing
Negative indexing means starting from the end.
-1 refers to the last item, -2 refers to the second last item etc.
Example
Print the last item of the tuple:
thistuple = ("apple", "banana", "cherry")
print(thistuple[-1])
Range of Indexes
You can specify a range of indexes by specifying where to start and where to end the range.
When specifying a range, the return value will be a new tuple with the specified items.
Example
Return the third, fourth, and fifth item:
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).
By leaving out the start value, the range will start at the first item.
Example
This example returns the items from the beginning to, but NOT included, "kiwi":
thistuple = ("apple", "banana", "cherry", "orange", "kiwi", "melon", "mango")
print(thistuple[:4])
By leaving out the end value, the range will go on to the end of the tuple.
Example
This example returns the items from "cherry" and to the end:
thistuple = ("apple", "banana", "cherry", "orange", "kiwi", "melon", "mango")
print(thistuple[2:])
Range of Negative Indexes
Specify negative indexes if you want to start the search from the end of the tuple.
Example
This example returns the items from index -4 (included) to index -1 (excluded)
thistuple = ("apple", "banana", "cherry", "orange", "kiwi", "melon", "mango")
print(thistuple[-4:-1])
Check if Item Exists
To determine if a specified item is present in a tuple use the in keyword.
Example
Check if "apple" is present in the tuple:
thistuple = ("apple", "banana", "cherry")
if "apple" in thistuple:
print("Yes, 'apple' is in
the fruits tuple")
17.3 Exercise
1. Which one of these is a tuple?
A. thistuple = ('apple', 'banana', 'cherry')
B. thistuple = ['apple', 'banana', 'cherry']
C. thistuple = {'apple', 'banana', 'cherry'}
D. thistuple = {apple, banana, cherry}
2. You can access tuple items by referring to the index number, but what is the index number of the first item?
A. 1
B. 0
C. -1
D. first
3. The given tuple is a nested tuple. Write a Python program to print the value 20.
Given:
tuple1 = ("Orange", [10, 20, 30], (5, 15, 25))
Expected Output:
20
4. Write a python program, use if, elif, else statement, to make a simple calculator.
Input:
First number:2
Operator (+, -, *, /): +
Second number:3
Expected Output:
Result: 5.0
-----
The answer hints:
1(A), 2(B)
3. The given tuple is a nested tuple. Write a Python program to print the value 20.
Given:
tuple1 = ("Orange", [10, 20, 30], (5, 15, 25))
Expected Output:
20
[code17_3.py]
tuple1 = ("Orange", [10, 20, 30], (5, 15, 25))
# understand indexing
# tuple1[0] = 'Orange'
# tuple1[1] = [10, 20, 30]
# list1[1][1] = 20
print(tuple1[1][1])
4. Write a python program, use if, elif, else statement, to make a simple calculator.
Input:
First number:2
Operator (+, -, *, /): +
Second number:3
Expected Output:
Result: 5.0
[code17_4.py]
# simple calculator
# get user input
num1 = float(input("First number:"))
operator = input("Operator (+, -, *, /): ")
num2 = float(input("Second number:"))
# perform the calculation based on the operator
if operator == "+":
result = num1 + num2
elif operator == "-":
result = num1 - num2
elif operator == "*":
result = num1 * num2
elif operator == "/":
if num2 == 0:
print("Error: Division by zero")
else:
result = num1 / num2
else:
print("Invalid operator")
result = None
# print the result if valid
if result is not None:
print("Result:", result)
Cập nhật: 7/11/2024
Bài sau: Python căn bản (18): Python Tuples (cont.)
-----
[Nội dung tham khảo từ w3schools, pynative và Internet]
Bạn muốn học Python căn bản tại Đà Lạt, liên hệ