Python data type: string, number, list, tuple, set and dictionary
In this section, you'll learn how to use Python as a computer, grasp Python's data types and take the first step towards Python programming.
In the previous section, we became familiar with the first Python program, adding two numbers and printing their sum out of the screen. In this section, you will learn how to use Python as a computer, learn numbers, strings, lists and take the first step towards Python programming.
Because the article will list the most important content of all data types in Python, it will be quite long. Each data type comes with a specific example so you can easily imagine.
Make sure you save this Python Document page to update the latest articles. Don't forget to do Python exercises to reinforce your knowledge.
Data type in Python
- 1. Turn in Python
- 2. Digital data type in Python
- Digital data types in Python
- Switch between numeric types in Python
- Python Decimal Module
- When should I use Decimal instead of floats?
- Fractions in Python
- Math in Python
- Use interpreter like pocket calculator
- 3. String (string)
- How to create a string in Python
- How to access the element of the string
- Change or delete the string
- Stringing
- Repeat and check the element of the string
- Python functions are built-in to work with strings
- Format () method to format the string
- The method is often used in string
- 4. List (list)
- How to create lists in Python
- Access the list element
- Slicing lists in Python
- Change or add elements to the list
- Delete or remove an element from the list in Python
- List method in Python
- List comprehension: How to create a new list briefly
- Check if the element is in the list
- For loop in list
- Python functions integrated with the list
- 5. Tuple
- Where is Tuple more than the list?
- Create a tuple
- Access the elements of tuple
- Change a tuple
- Delete tuple
- Methods and functions used with tuple in Python
- Check the element in tuple
- Loop through the elements of tuple in Python
- 6. Set
- How to create a set
- How to change set in Python
- Delete element from set
- Set operators in Python
- The methods used on the set
- Check element in set
- Repeat through the set element
- The function is often used on set
- Frozenset in Python
- 7. Dictionary
- How to create dictionary in Python
- Access the dictionary element
- Change, add element to dictionary
- Delete the dictionary element
- Methods and functions for dictionary
- Dictionary comprehension in Python
- Check and loop through the element in dictionary
- 8. Switch between data types
- 9. The first step towards programming
1. Turn in Python
Variables are a location in memory used to store data (values). The variable is uniquely named to distinguish between different memory locations. The rules for writing a variable name are the same as the rules for writing identifiers in Python.
In Python, you don't need to declare the variable before using it, just assign a variable a value and it will exist. There is also no need to declare variable type, the variable type will be automatically received based on the value you assigned to the variable.
Assign values to variables:
To assign a value to the variable, use the = operator. Any kind of value can be assigned to a valid variable.
For example:
hoa = "Hồng" la = 3 canh = 5.5
Above are three assignment statements, "Pink" is a character string, assigned to the flower variable, 3 is an integer and is assigned to la, 5.5 is a decimal number and assigned to the soup.
Assign multiple values:
In Python you can perform multiple assignments in a command like this:
hoa, la, canh = "Hồng", 3, 5.5
If you want to assign the same value to multiple variables, you can write the following command:
hoa, la, canh = 3
The above command will assign a value of 3 to all three variables, flowers, la and soup.
2. Digital data type in Python
Digital data types in Python
Python supports integers, decimals, and complex numbers, which in turn are defined as int, float, and complex classes in Python. Integers and decimals are distinguished by the presence or absence of the decimal point. For example: 5 is an integer, 5.0 is a decimal number. Python also supports complex numbers and uses the suffix j
or J
to indicate the virtual part. For example: 3+5j
. In addition to int
and float
, Python supports two more types of numbers, Decimal
and Fraction
.
We will use the type () function to check which variable or value belongs to the class and isinstance () to check if they belong to any particular class.
a = 9 # Output: print(type(a)) # Output: print(type(5.0)) # Output: (10+2j) b = 8 + 2j print(b + 2) # Kiểm tra xem b có phải là số phức không # Output: True print(isinstance(b, complex))
a = 9 # Output: print(type(a)) # Output: print(type(5.0)) # Output: (10+2j) b = 8 + 2j print(b + 2) # Kiểm tra xem b có phải là số phức không # Output: True print(isinstance(b, complex))
a = 9 # Output: print(type(a)) # Output: print(type(5.0)) # Output: (10+2j) b = 8 + 2j print(b + 2) # Kiểm tra xem b có phải là số phức không # Output: True print(isinstance(b, complex))
Python integers are not limited to lengths, decimals are limited to 16 numbers after the decimal point.
The numbers they work on are usually a factor of 10, but computer programmers (usually embedded programmers) need to work with binary, hexadecimal and octal systems. To represent these coefficients in Python, we put an appropriate prefix before that number.
Coefficient prefix for Python numbers:
Number system Binary Prefix '0b' or '0B' Octal system '0o' or '0O' Hexadecimal '0x' or '0X'(You put the prefix but no sign ").
Here is an example of using coefficient prefixes in Python, and when using the print () function to print their values to the screen, we get the corresponding number in the factor of 10.
# Output: 187 print(0b10111011) # Output: 257 (250 + 7) print(0xFA + 0b111) # Output: 15 print(0o17)
Switch between numeric types in Python
We can convert this number type to another number. This is also called coercion. Operations such as addition and subtraction will implicitly convert integers to decimal numbers (automatically) if there is an operator in the operation that is a decimal.
For example: If you perform the addition of integer 2 and decimal number 3.0, then 2 will be forced to convert into decimal 2.0 and the result will be a 5.0 decimal.
>>> 2 + 3.0 5.0
We can use built-in Python functions like int (), float () and complex () to switch between numeric types explicitly. These functions can even be converted from strings.
>>> int(3.6) 3 >>> int(-1.2) -1 >>> float(7) 7.0 >>> complex('2+8j') (2+8j)
When converting from decimal to integer, the number will be dropped, only the integer part is taken.
Python Decimal Module
The built-in float class in Python can surprise us a bit. Normally, if calculating 1.1 and 2.2, we think the result will be 3.3, but it doesn't seem to be so. If you check the correctness and error of this operation in Python, the result will be False.
>>> (1.1 + 2.2) == 3.3 False
What happened?
This is because decimal numbers are implemented in computer hardware in the form of binary fractions, because computers only understand binary numbers (0 and 1), so most of the decimal fraction we know , cannot be stored correctly in the computer.
For example, we cannot represent 1/3 fraction as a decimal number, since it is an infinite decimal number, with numbers after the decimal point infinitely long, we can only estimate it. .
When converting decimal 0.1, it will lead to infinitely long binary part of 0.000110011001100110011 . and the computer only stores part of the finite number after the sign. Its just. Therefore, the stored number is only approximately 0.1 but never equal to 0.1. That is why, the addition we mentioned above does not produce the results we expect. That is the limit of computer hardware, not Python error.
Now try typing the addition above into Python to see what the result is:
>>> 1.1+2.2 3.3000000000000003
To fix this problem, we can use the Python Decimal module. While the float only takes 16 digits after the decimal point, the Decimal module allows to customize the length of the number.
import decimal # Output: 0.1 print(0.1) # Output: 0.1000000000000000055511151231257827021181583404541015625 print(decimal.Decimal(0.1))
This module is used when we want to perform operations with decimal numbers to get the results we have learned at school.
This is also quite important, for example 25.50kg will be more accurate than 25.5kg, because 2 decimal places are still more accurate than 1 digit.
from decimal import Decimal # Output: 3.3 print(Decimal('1.1') + Decimal('2.2')) # Output: 10.000 print(Decimal('4.0') * Decimal('2.50'))
If you want a more concise code, you can enter the Decimal module and edit the module name to D.
from decimal import Decimal as D # Output: 3.3 print(D('1.1') + D('2.2')) # Output: 10.000 print(D('4.0') * D('2.50'))
In this code, enter the Decimal module and edit its name to D, the result is unchanged from the above code.
You can ask in the multiplication section, why not use Decimal number to multiply it by adding 0 after 4 and 2.5. The answer is efficiency, operations with floats are faster than Decimal operations.
When should I use Decimal instead of floats?
We often use Decimal in the following cases:
- When creating a financial application, it is necessary to represent the decimal part exactly.
- When you want to control the accuracy of numbers.
- When you want to do the math just like you did at school.
Fractions in Python
Python provides fractions related to fractions through fractions modules. A fraction with a numerator and denominator, both are integers. We can create Fraction objects in many different ways:
import fractions # Tạo phân số từ số thập phân print(fractions.Fraction(4.5)) # Output: 9/2 # Tạo phân số từ số nguyên # Code by TipsMake.com print(fractions.Fraction(9)) # Output: 9 # Tạo phân số bằng cách khai báo tử, mẫu số print(fractions.Fraction(2,5)) # Output: 2/5
When creating fractions from floats, we can get unusual results, which is due to computer hardware limitations as discussed in the decimal module.
In particular, you can initialize a fraction from the string. This is the preferred initialization method when using decimal numbers.
import fractions # Khởi tạo phân số từ float print(fractions.Fraction(0.1)) # Output: 3602879701896397/36028797018963968 # Khởi tạo phân số từ string # Code by TipsMake.com print(fractions.Fraction('0.1')) # Output: 1/10
Fraction data types fully support basic operations such as addition, subtraction, multiplication, division and logic:
# Output: 1 print(F(2,5) + F(3,5)) # Output: 3/5 print(F(2,5) + F(1,5)) # Output: 7/1 print(1 / F(3,7)) # Output: False print(F(-2,9) > 0) # Output: True print(F(-2,9) < 0)
Math in Python
Python provides math and random modules to solve other math problems such as trigonometry, logarithm, probability and statistics, etc. Since the math module has many functions and attributes, I calculated will do a separate article to list them. Below is an example of math in Python.
from fractions import Fraction as F import math # Output: 3.141592653589793 print(math.pi) # Output: -1.0 print(math.cos(math.pi)) # Output: 22026.465794806718 print(math.exp(10)) # Output: 2.0 print(math.log2(4)) # Output: 1.1752011936438014 print(math.sinh(1)) # Output: 40320 print(math.factorial(8))
Use interpreter like pocket calculator
The interpreter acts as a simple calculator: You can enter a calculation and it will write the value. Expression syntax is quite simple: operators like +, -, * and / work like most other programming languages (Pascal, C), parentheses () can be used to group . For example:
>>> 2 + 2 4 >>> 50 - 5*6 20 >>> (50 - 5*6) / 4 5.0 >>> 8 / 5 # phép chia luôn trả về một số dạng thập phân với dấu chấm 1.6
Integers (eg 2
, 4
, 20
) are of type int
, decimal numbers (such as 5.0
, 1.6
) are of type float
.
Divide ( /
) always returns type float. To perform the partial division (remove the numbers after the decimal point) you can use the operator //
; To calculate the remainder, use %
as the example below:
>>> 17 / 3 # phép chia thường trả về số thập phân 5.666666666666667 >>> >>> 17 // 3 # phép chia lấy số nguyên, loại bỏ phần sau dấu thập phân 5 >>> 17 % 3 # toán tử % trả về số dư của phép chia 2 >>> 5 * 3 + 2 # thương * số chia + số dư 17
With Python, you can use the **
operator to calculate the exponent:
>>> 5 ** 2 # 5 bình phương 25 >>> 2 ** 7 # 2 mũ 7 128
The equal sign =
is used to assign a value to a variable. After that, no results will be displayed before the next command prompt:
>>> width = 20 >>> height = 5 * 9 >>> width * height 900
If a variable is not defined (assign value), try to use that variable, you will get the following error:
>>> n # bạn đang cố truy cập vào biến n chưa được gán giá trị Traceback (most recent call last): File "", line 1, in NameError: name 'n' is not defined
Python fully supports floating point, the calculation has both integers and decimals, the result will return the number in decimal (verb: operator with mixed type operand converts integer operand to decimal):
>>> 4 * 3.75 - 1 14.0
In interactive mode, the last printed expression will be assigned to variable _
, making it easier to perform further calculations. For example:
>>> tax = 12.5 / 100 >>> price = 100.50 >>> price * tax 12.5625 >>> price + _ 113.0625 >>> round(_, 2) 113.06
You should treat this variable as read-only, do not assign a value to it - because creating a variable of the same name will take up this default variable and no longer do good things like that.
3. String (string)
String in Python is a sequence of characters. Computers do not handle characters, they only work with binary numbers. Although you can see the characters on the screen, they are stored and processed internally as a combination of numbers 0 and 1. Converting the numeric character is called encoding and the reverse process called decoding. ASCII and Unicode are 2 of the commonly used common encodings.
In Python, string is a sequence of Unicode characters. Unicode includes all characters in all languages and provides uniformity in encoding.
How to create a string in Python
Besides numbers, Python can also manipulate strings, represented in many ways. They can be put in single quotes ( '.'
) or double ( "."
) with the same result. used to "escape" these 2 quotes.
>>> 'spam eggs' # dấu nháy đơn 'spam eggs' >>> 'doesn't' # sử dụng ' để viết dấu nháy đơn. "doesn't" >>> "doesn't" # .hoặc sử dụng dấu nháy kép "doesn't" >>> '"Yes," he said.' '"Yes," he said.' >>> ""Yes," he said." '"Yes," he said.' >>> '"Isn't," she said.' '"Isn't," she said.'
In the interactive interpreter, the result string consists of a quotation mark and special "escape" characters used. Although the output looks a bit different from the input (the enclosed quotes may change), these two strings are equivalent. The string is written in quotation marks when the string contains single quotes and no double quotes, otherwise it will be written in single quotes. The print () function creates a more readable output string, by skipping the apostrophe enclosed and printing special characters, "hiding" the quotes:
>>> '"Isn't," she said.' '"Isn't," she said.' >>> print('"Isn't," she said.') "Isn't," she said. >>> s = 'First line.nSecond line.' # n nghĩa là dòng mới >>> s # không có print(), n sẽ được viết trong kết quả đầu ra 'First line.nSecond line.' >>> print(s) # có print(), n sẽ tạo ra dòng mới First line. Second line.
If you do not want the characters added by interpreted by the interpreter as a special character, use the raw string by adding
r
to the first quotation mark:
>>> print('C:somename') # ở đây n là dòng mới! C:some ame >>> print(r'C:somename') # thêm r trước dấu nháy C:somename
String strings can be written on multiple lines by using 3 quotes: """."""
or '''.'''
. End lines automatically included in the string, but can prevent this by adding at the end of the line. For example:
print(""" Usage: thingy [OPTIONS] -h Display this usage message -H hostname Hostname to connect to """)
This is the result (the new original line is not counted):
Here is a list of all escape sequences supported by Python:
Escape SequenceLayewewline Backslash and new line are ignored Backslash 'Single quotation mark' Double quotes aASCII Bell
b ASCII Backspace f ASCII Formfeed n ASCII Linefeed r ASCII Carriage Return t ASCII Horizontal Tab v ASCII Vertical Tab ooo The character has an octal value ooo xHH The hexadecimal character is HHFor example: Run each command individually in the compiler to see your results.
>>> print("C:Python32TipsMake.com") C:Python32TipsMake.com >>> print("In dòng nàynthành 2 dòng") In dòng này thành 2 dòng >>> print("In giá trị x48x45x58") In giá trị HEX >>>
How to access the element of the string
Strings can be indexed with the first character numbered 0. There is no separate character type, each character is simply a number:
>>> word = 'Python' >>> word[0] # ký tự ở vị trí số 0 'P' >>> word[5] # ký tự ở vị trí số 5 'n'
Index can also be negative, start counting from the right:
>>> word[-1] # last character 'n' >>> word[-2] # second-last character 'o' >>> word[-6] 'P'
Note that since -0 is similar to 0, negative indicators start at -1.
In addition to numbering, slices are also supported. While the index is used to retrieve individual characters, slices will allow you to retrieve substring:
>>> word[0:2] # các ký tự từ vị trí 0 (bao gồm) đến 2 (loại trừ) 'Py' >>> word[2:5] # các ký tự từ vị trí 2 (bao gồm) đến 5 (loại trừ) 'tho'
Notice how the characters are retained and excluded. It always ensures that s[:i] + s[i:]
equal to s
:
>>> word[:2] + word[2:] 'Python' >>> word[:4] + word[4:] 'Python'
The index in the chain cut has a pretty default setting, there are 2 indexes that are ignored by default, 0 and the size of the cut string.
>>> word[:2] # các ký tự từ đầu đến vị trí thứ 2 (loại bỏ) 'Py' >>> word[4:] # các ký tự từ vị trí thứ 4(lấy) đến hết 'on' >>> word[-2:] # các ký tự thứ hai tính từ cuối lên (lấy) đến hết 'on'
Another way to remember how to cut the work sequence is to visualize the indicators as partitions between characters, with the leftmost character being numbered 0. Then, the last character on the right, in string n characters will have an index n, for example:
+---+---+---+---+---+---+ | P | y | t | h | o | n | +---+---+---+---+---+---+ 0 1 2 3 4 5 6 -6 -5 -4 -3 -2 -1
The first row of numbers brings the position of the index from 0 to 6 in the series. The second row is the corresponding negative indicators. When cutting from i to j will include all characters between i and j, respectively.
For non-negative indicators, the length of a slice is the difference of the indicators, if both are within the limit. For example, the length of word [1: 3] is 2.
Trying to use an index that is too large will return an error:
>>> word[42] # từ chỉ có 6 ký tự Traceback (most recent call last): File "", line 1, in IndexError: string index out of range
However, indexes outside the slice range are still handled neatly when used to cut:
>>> word[4:42] # cắt ký tự từ vị trí thứ 4 đến 42 'on' >>> word[42:] # cắt ký tự sau vị trí 42 ''
Change or delete the string
Python strings cannot be changed - they are fixed.Therefore, if you intentionally assign a character to an indexed location, you will receive an error message:
>>> word[0] = 'J' . TypeError: 'str' object does not support item assignment >>> word[2:] = 'py' . TypeError: 'str' object does not support item assignment
If another string is needed, the best way is to create a new one:
>>> 'J' + word[1:] 'Jython' >>> word[:2] + 'py' 'Pypy'
You cannot delete or remove characters from the string, but like tuple, you can delete the entire string, using the del keyword:
qtm_string = 'quantrimang.com' del qtm_string # Output: NameError: name 'qtm_string' is not defined qtm_string
Stringing
Strings can be joined together by the +
operator and replaced by *
:
>>> # thêm 3 'un' vào sau 'ium' >>> 3 * 'un' + 'ium' 'unununium'
Two or more characters in the form of strings (ie, characters in the quotes) are joined automatically.
>>> 'Py' 'thon' 'Python'
This feature only works with string literal, not with variables or expressions:
>>> prefix = 'Py' >>> prefix 'thon' # không thể nối một biến với một chuỗi . SyntaxError: invalid syntax >>> ('un' * 3) 'ium' . SyntaxError: invalid syntax
If you want to join variables together or variables with strings, use the +
sign:
>>> prefix + 'thon' 'Python'
This feature is especially useful when you want to break long strings into shorter strings:
>>> text = ('Put several strings within parentheses ' . 'to have them joined together.') >>> text 'Put several strings within parentheses to have them joined together.'
If you want to join strings in many different lines, use parentheses:
>>> # sử dụng () >>> s = ('Xin ' . 'chào!') >>> s 'Xin chào!'
Repeat and check the element of the string
Like list and tuple, you also use the for loop when you need to loop through a string, like for example counting the number of "i" characters in the following string:
count = 0 for letter in 'TipsMake.com': if(letter == 'i'): count += 1 # Output: Có 1 chữ i được tìm thấy print('Có', count,'chữ i được tìm thấy')
To check if a substring is in the string, use the keyword print, as follows:
>>> 'quantrimang' in 'quantrimang.com' True >>> 'python' in 'quantrimang.com' False >>>
Python functions are built-in to work with strings
There are two most common functions when working with strings in Python: enumerate () and len ().
The len()
function is built into Python, which returns the length of the string:
>>> s = 'supercalifragilisticexpialidocious' >>> len(s) 34
The enumerate () function returns the listed object, containing the value and index pairs of the element in the string, which is quite useful while looping.
qtm_str = 'Python' # enumerate() qtm_enum = list(enumerate(qtm_str)) # Output: list(enumerate(qtm_str) = [(0, 'P'), (1, 'y'), (2, 't'), (3, 'h'), (4, 'o'), (5, 'n')] print('list(enumerate(qtm_str) = ', qtm_enum)
Format () method to format the string
The format () method is very flexible and powerful when used to format strings. The string format contains the {} mark as a placeholder or a replacement field to receive the replacement value. You can also use position or keyword arguments to specify the order.
# default(implicit) order thu_tu_mac_dinh = "{}, {} và {}".format('Quản','Trị','Mạng') print('n--- Thứ tự mặc định ---') print(thu_tu_mac_dinh) # sử dụng đối số vị trí để sắp xếp thứ tự vi_tri_thu_tu= "{1}, {0} và {2}".format('Quản','Trị','Mạng') print('n--- Thứ tự theo vị trí ---') print(vi_tri_thu_tu) # sử dụng từ khóa để sắp xếp thứ tự tu_khoa_thu_tu = "{s}, {b} và {j}".format(j='Quản',b='Trị',s='Mạng') print('n--- Thứ tự theo từ khóa ---') print(tu_khoa_thu_tu)
We have the results when running the above code as follows:
--- Thứ tự mặc định --- Quản, Trị và Mạng --- Thứ tự theo vị trí --- Trị, Quản và Mạng --- Thứ tự theo từ khóa --- Mạng, Trị và Quản
The format () method can have optional format specifications. They are separated from the field name with a:. For example, you can align left <, right> or center ^ a string in the given space. It is possible to format integers such as binary and hexadecimal numbers; Decimals can be rounded or displayed in exponential form. There are many formats you can use.
>>> # Định dạng số nguyên >>> "Khi chuyển {0} sang nhị phân sẽ là {0:b}".format(12) 'Khi chuyển 12 sang nhị phân sẽ là 1100' >>> # Định dạng số thập phân >>> "Số thập phân {0} ở dạng mũ sẽ là {0:e}".format(1566.345) 'Số thập phân 1566.345 ở dạng mũ sẽ là 1.566345e+03' >>> # Làm tròn số thập phân >>> "1 phần 3 là: {0:.3f}".format(1/3) '1 phần 3 là: 0.333' >>> # căn chỉnh chuỗi >>> "|{:<10}|{:^10}|{:>10}|".format('Quản','Trị','Mạng') '|Quản | Trị | Mạng|'
Old style string format:
You can format the string in Python about sprintf () style used in programming language C with% operator.
>>> x = 15.1236789 >>> print('Giá trị của x là %3.2f' %x) Giá trị của x là 15.12 >>> print('Giá trị của x là %3.4f' %x) Giá trị của x là 15.123712.3457
The method is often used in string
There are many methods built into Python to work with strings. In addition to the format () mentioned above, there is lower (), upper (), join (), split (), find (), replace (), etc. .
>>> "QuanTriMang.Com".lower() 'quantrimang.com' >>> "QuanTriMang.Com".upper() 'QUANTRIMANG.COM' >>> "Quan Tri Mang Chấm Com".split() ['Quan', 'Tri', 'Mang', 'Chấm', 'Com'] >>> ' '.join(['Quan', 'Tri', 'Mang', 'Chấm', 'Com']) 'Quan Tri Mang Chấm Com'' >>> 'Quan Tri Mang Chấm Com'.find('Qua') 0 >>> 'Quan Tri Mang Chấm Com'.replace('Chấm','.') 'Quan Tri Mang . Com'
4. List (list)
Python provides a variety of complex data, often called sequences, used to group different values. The most versatile is the list (list).
How to create lists in Python
In Python, the list is represented by a series of values, separated by commas, within []. Lists may contain multiple items of different types, but usually items with the same type.
>>> squares = [1, 4, 9, 16, 25] >>> squares [1, 4, 9, 16, 25]
List unlimited number of items, you can have many different data types in the same list, such as string, integer, decimal, .
list1 = [] # list rỗng list2 = [1, 2, 3] # list số nguyên list3 = [1, "Hello", 3.4] # list với kiểu dữ liệu hỗn hợp
You can also create nested lists (lists contained in the list), for example:
a = ['a', 'b', 'c'] n = [1, 2, 3] x = [a, n] print (x) # Output: [['a', 'b', 'c'], [1, 2, 3]] print (x[0]) # Output: ['a', 'b', 'c'] print(x[0][1]) # Output: b
Or declare a nested list from the beginning:
list4 = [mouse", [8, 4, 6], ['a']]
Access the list element
There are many different ways to access the element of a list:
Index (index) of the list:
Use the index [] operator to access an element of the list. Index starts at 0, so a list with 5 elements will have an index of 0 to 4. Accessing an index element other than the index of the list will give rise to an IndexError error. Index must be an integer, cannot use float, or other data type, will create a TypeError error.
qtm_list = ['q','u','a','n','t','r','i','m','a','n','g','.','c','o','m'] # TypeError: list indices must be integers or slices, not float # TypeError: index của list phải là số nguyên hoặc slice, không phải số thập phân qtm_list[2.0]
Nested lists can be accessed by nested index:
qtm_list = ['q','u','a','n','t','r','i','m','a','n','g','.','c','o','m'] # Output: q print(qtm_list[0]) # Output: a print(qtm_list[2]) # Output: t print(qtm_list[4]) # List lồng nhau ln_list = ["Happy", [1,3,5,9]] # Index lồng nhau # Output: a print(ln_list[0][1]) # Output: 9 print(ln_list[1][3])
Negative Index:
Python allows negative indexing for strings. Index -1 is the last element, -2 is the last element from the last. Simply said, index is negative when you count the element of the string backwards from the beginning to the beginning.
qtm_list = ['q','u','a','n','t','r','i','m','a','n','g','.','c','o','m'] # Code by TipsMake.com # Output: m print(qtm_list[-1]) # Output: i print(qtm_list[-9])
Slicing lists in Python
Python allows access to a range of elements of the list by using the slice operator: (colon). Every list cut action returns a new list containing the required elements.
qtm_list = ['q','u','a','n','t','r','i','m','a','n','g','.','c','o','m'] # Code by TipsMake.com # Output: ['u', 'a', 'n', 't'] print(qtm_list[1:5]) # Output: ['q', 'u', 'a', 'n', 't', 'r', 'i'] print(qtm_list[:-8]) # Output: ['n', 'g', '.', 'c', 'o', 'm'] print(qtm_list[9:])
To slice the list, you only need to use the sign: between the two indexes to retrieve the elements. [1: 5] will take elements 1 to 5, [: -8] taken from 0 to -8, .
If the following cut action is performed, it will return a new list as a copy of the original list:
qtm_list = ['q','u','a','n','t','r','i','m','a','n','g','.','c','o','m'] # Output: ['q', 'u', 'a', 'n', 't', 'r', 'i', 'm', 'a', 'n', 'g', '.', 'c', 'o', 'm'] print(qtm_list[:])
Change or add elements to the list
List also supports operations like list join:
>>> squares + [36, 49, 64, 81, 100] [1, 4, 9, 16, 25, 36, 49, 64, 81, 100]
Unlike strings, fixed, the list is a data type that can be changed. For example, you can change items in the list:
>>> cubes = [1, 8, 27, 65, 125] # có vẻ sai sai >>> 4 ** 3 # lập phương của 4 là 64, không phải 65! 64 >>> cubes[3] = 64 # thay thế giá trị sai >>> cubes [1, 8, 27, 64, 125]
You can also add new items to the end of the list using methods, such as append ():
>>> cubes.append(216) # thêm lập phương của 6 >>> cubes.append(7 ** 3) # và lập phương của 7 >>> cubes [1, 8, 27, 64, 125, 216, 343]
Assigning slices can also be done and can even change the size of the list or delete it completely:
>>> letters = ['a', 'b', 'c', 'd', 'e', 'f', 'g'] >>> letters ['a', 'b', 'c', 'd', 'e', 'f', 'g'] >>> # thay thế vài giá trị >>> letters[2:5] = ['C', 'D', 'E'] >>> letters ['a', 'b', 'C', 'D', 'E', 'f', 'g'] >>> # giờ thì xóa chúng >>> letters[2:5] = [] >>> letters ['a', 'b', 'f', 'g'] >>> # xóa list bằng cách thay tất cả các phần tử bằng một list rỗng >>> letters[:] = [] >>> letters []
Wool functions () can also be applied to lists:
>>> letters = ['a', 'b', 'c', 'd'] >>> len(letters) 4
Delete or remove an element from the list in Python
You can delete one or more elements from the list using the del keyword, you can delete the list completely.
my_list = ['q','u','a','n','t','r','i','m','a','n','g','.','c','o','m'] # xóa phần tử có index là 2 del my_list[2] # Output: ['q', 'u', 'n', 't', 'r', 'i', 'm', 'a', 'n', 'g', '.', 'c', 'o', 'm'] print(my_list) # xóa phần tử có index từ 1 đến 7 del my_list[1:7] # Output: ['q', 'a', 'n', 'g', '.', 'c', 'o', 'm'] print(my_list) # xóa toàn bộ list my_list del my_list # Error: NameError: name 'my_list' is not defined print(my_list)
You can also use remove () to remove a given element or pop () to remove an element at a certain index. pop () removes the element and returns the last element if the index is not specified. This helps to deploy the list in the form of a stack (data structure first in last out - first, last).
In addition, the clear () method is also used to empty a list (deleting all elements in the list).
my_list = ['q','u','a','n','t','r','i','m','a','n','g','.','c','o','m'] my_list.remove('.') # Output: ['q', 'u', 'a', 'n', 't', 'r', 'i', 'm', 'a', 'n', 'g', 'c', 'o', 'm'] print(my_list) # Output: n print(my_list.pop(3)) # Output: ['q', 'u', 'a', 't', 'r', 'i', 'm', 'a', 'n', 'g', 'c', 'o', 'm'] print(my_list) # Output: m print(my_list.pop()) # Output: ['q', 'u', 'a', 't', 'r', 'i', 'm', 'a', 'n', 'g', 'c', 'o'] print(my_list) my_list.clear() # Output: [] (list rỗng) print(my_list)
The last way to delete elements in a list is to assign an empty list to the element slices.
>>> my_list = ['q','u','a','n','t','r','i','m','a','n','g','.','c','o','m'] >>> my_list[11:15]=[] >>> my_list ['q', 'u', 'a', 'n', 't', 'r', 'i', 'm', 'a', 'n', 'g']
List method in Python
The methods available for lists in Python include:
- append () : Add an element to the end of the list.
- extend () : Add all elements of the current list to another list.
- insert () : Insert an element into the given index.
- remove () : Delete the element from the list.
- pop () : Delete the element from the list and return the element at the given index.
- clear () : Delete all elements of the list.
- index () : Returns the index of the first matching element.
- count () : Returns the number of counted elements in the list as an argument.
- sort () : Arrange the elements in the list in ascending order.
- reverse () : Reverse the order of elements in the list.
- copy () : Returns the copy of the list.
For example:
QTM = [9,8,7,6,8,5,8] # Output: 2 print(QTM.index(7)) # Output: 3 print(QTM.count(8)) QTM.sort() # Output: [5, 6, 7, 8, 8, 8, 9] print(QTM) QTM.reverse() # Output: [9, 8, 8, 8, 7, 6, 5] print(QTM)
Example 2:
QTM = ['q','u','a','n','t','r','i','m','a','n','g','.','c','o','m'] # Output: 3 print(QTM.index('n')) # Output: 2 print(QTM.count('a')) QTM.sort() # Output: ['.', 'a', 'a', 'c', 'g', 'i', 'm', 'm', 'n', 'n', 'o', 'q', 'r', 't', 'u'] print(QTM) QTM.reverse() # Output: ['u', 't', 'r', 'q', 'o', 'n', 'n', 'm', 'm', 'i', 'g', 'c', 'a', 'a', '.'] print(QTM)
List comprehension: How to create a new list briefly
List comprehension is an expression associated with a for statement that is enclosed in square brackets [].
For example:
cub3 = [3 ** x for x in range(9)] # Output: [1, 3, 9, 27, 81, 243, 729, 2187, 6561] print(cub3)
The above code is equivalent to:
cub3 = [] for x in range (9): cub3.append(3**x) print(cub3)
In addition to for, if can also be used in a list comprehension of Python. The if command can filter the elements in the current list to create a new list. Here is an example:
cub3 = [3 ** x for x in range(9) if x > 4] # Output: [243, 729, 2187, 6561] print(cub3) so_le = [x for x in range (18) if x % 2 == 1] # Output: [1, 3, 5, 7, 9, 11, 13, 15, 17] print(so_le) noi_list = [x+y for x in ['Ngôn ngữ ','Lập trình '] for y in ['Python','C++']] # Output: ['Ngôn ngữ Python', 'Ngôn ngữ C++', 'Lập trình Python', 'Lập trình C++'] print(noi_list)
Check if the element is in the list
Use the keyword in to check if an element is already in the list. If the element already exists, the result is True, and vice versa will return False.
QTM = ['q','u','a','n','t','r','i','m','a','n','g','.','c','o','m'] # Output: True print('q' in QTM) # Output: True print('.' in QTM) # Output: False print('z' in QTM)
For loop in list
Use the for loop to loop through the elements in the list as shown below:
for ngon_ngu in ['Python','Java','C']: print("Tôi thích lập trình",ngon_ngu)
The result returned will be as follows:
Tôi thích lập trình Python Tôi thích lập trình Java Tôi thích lập trình C
Python functions integrated with the list
Built-in Python functions like all (), any (), enumerate (), len (), max (), min (), list (), sorted (), . are often used with lists for real Show different tasks.
- all () : Returns true if all elements of the list are true or list empty.
- any () : Returns True when any element in the list is true. If the list is empty the function returns False.
- enumerate () : Returns the enumerate, containing index object and the value of all elements of the list as tuple.
- len () : Returns the length (number of elements) of the list.
- list () : Convert an object that can loop (tuple, string, set, dictionary) into a list.
- max () : Returns the largest element in the list.
- min () : Returns the smallest element in the list.
- sorted () : Returns the new sorted list.
- sum () : Returns the sum of all elements in the list.
5. Tuple
Tuple in Python is a sequence of ordered elements like list. The difference between list and tuple is that we cannot change the elements in the tuple when assigned, but in the list, the elements can change.
Tuple is often used for data that does not allow modifications and is faster than lists because it cannot be changed automatically. A tuple is defined by parentheses (), elements in tuple are separated by commas (,).
For example:
t = (10, "quan tri mang", 2j)
You can use the [] cut operator to extract the element in tuple but cannot change its value.
t = (10, "quan tri mang", 2j) #t[0:2] = (10, 'quan tri mang') print("t[0:2] = ", t[0:2])
Run the above code we get the result:
t[0:2] = (10, 'quan tri mang')
Where is Tuple more than the list?
Because tuples and lists are quite similar, they are often used in similar situations. However, tuples still have certain advantages over the list, such as:
- Tuple is often used for heterogeneous (different) data types and lists often use for identical (identical) data types.
- Since tuple cannot be changed, iterating through tuple elements is faster than list. So in this case, tuple is a bit more dominant than the list.
- Tuple contains unchanged elements, which can be used as keys for dictionary. With the list, this cannot be done.
- If there is data that does not change its deployment as a tuple, it will ensure that the data is write-protected.
Create a tuple
Tuple is created by placing all of its elements in parentheses (), separated by commas. You can remove parentheses if you want, but add it to make the code more clear.
Tuple is not limited to the number of elements and can have many different data types such as integers, decimals, lists, strings, .
# Tuple rỗng # Output: () my_tuple = () print(my_tuple) # tuple số nguyên # Output: (2, 4, 16, 256) my_tuple = (2, 4, 16, 256) print(my_tuple) # tuple có nhiều kiểu dữ liệu # Output: (10, "TipsMake.com", 3.5) my_tuple = (10, "TipsMake.com", 3.5) print(my_tuple) # tuple lồng nhau # Output: ("QTM", [2, 4, 6], (3, 5, 7)) my_tuple = ("QTM", [2, 4, 6], (3, 5, 7)) print(my_tuple) # tuple có thể được tạo mà không cần dấu () # còn gọi là đóng gói tuple # Output: (10, "TipsMake.com", 3.5) my_tuple = 10, "TipsMake.com", 3.5 print(my_tuple) # mở gói (unpacking) tuple cũng có thể làm được # Output: # 10 # TipsMake.com # 3.5 a, b, c = my_tuple print(a) print(b) print(c)
Creating a tuple has only a little bit of a complicated element, if you create the usual way of putting that element in the sign () is not enough, you need to add a comma to indicate that this is tuple.
# tạo tuple chỉ với () # Output: my_tuple = ("TipsMake.com") print(type(my_tuple)) # khi thêm dấu phẩy vào cuối # Output: my_tuple = ("TipsMake.com",) print(type(my_tuple)) # dấu () là tùy chọn, bạn có thể bỏ nếu thích # Output: my_tuple = "TipsMake.com", print(type(my_tuple))
# tạo tuple chỉ với () # Output: my_tuple = ("TipsMake.com") print(type(my_tuple)) # khi thêm dấu phẩy vào cuối # Output: my_tuple = ("TipsMake.com",) print(type(my_tuple)) # dấu () là tùy chọn, bạn có thể bỏ nếu thích # Output: my_tuple = "TipsMake.com", print(type(my_tuple))
# tạo tuple chỉ với () # Output: my_tuple = ("TipsMake.com") print(type(my_tuple)) # khi thêm dấu phẩy vào cuối # Output: my_tuple = ("TipsMake.com",) print(type(my_tuple)) # dấu () là tùy chọn, bạn có thể bỏ nếu thích # Output: my_tuple = "TipsMake.com", print(type(my_tuple))
# tạo tuple chỉ với () # Output: my_tuple = ("TipsMake.com") print(type(my_tuple)) # khi thêm dấu phẩy vào cuối # Output: my_tuple = ("TipsMake.com",) print(type(my_tuple)) # dấu () là tùy chọn, bạn có thể bỏ nếu thích # Output: my_tuple = "TipsMake.com", print(type(my_tuple))
Access the elements of tuple
There are many different ways to access the elements of a tuple, quite similar to the list, so I don't take specific examples, you can review the list of the list.
Index: Sử dụng toán tử index [] để truy cập vào phần tử trong tuple với index bắt đầu bằng 0. Nghĩa là nếu tuple có 6 phần tử thì index của nó sẽ bắt đầu từ 0 đến 5. Nếu cố gắn truy cập đến index 6, 7 thì sẽ tạo lỗi IndexError. Index bắt buộc phải là số nguyên, mà không thể là số thập phân hay bất kỳ kiểu dữ liệu nào khác, nếu không sẽ tạo lỗi TypeError. Những tuple lồng nhau được truy cập bằng cách sử dụng index lồng nhau:
# tuple lồng nhau n_tuple = ("TipsMake.com", [2, 6, 8], (1, 2, 3)) # index lồng nhau # Output: 'r' print(n_tuple[0][5]) # index lồng nhau # Output: 8 print(n_tuple[1][2])
Index âm: Python cho phép lập chỉ mục âm cho các đối tượng dạng chuỗi. Index -1 tham chiếu đến phần tử cuối cùng, -2 là thứ 2 tính từ cuối tính lên.
Cắt lát: Có thể truy cập đến một loạt phần tử trong tuple bằng cách sử dụng toán tử cắt lát : (dấu 2 chấm).
Thay đổi một tuple
Không giống như list, tuple không thể thay đổi. Điều này có nghĩa là các phần tử của một tuple không thể thay đổi một khi đã được gán. Nhưng, nếu bản thân phần tử đó là một kiểu dữ liệu có thể thay đổi (như list chẳng hạn) thì các phần tử lồng nhau có thể được thay đổi. Chúng ta cũng có thể gán giá trị khác cho tuple (gọi là gán lại - reassignment).
my_tuple = (1, 3, 5, [7, 9]) # không thể thay đổi phần tử của tuple # Nếu bạn bỏ dấu # ở dòng 8 # Bạn sẽ nhận được lỗi: # TypeError: 'tuple' object does not support item assignment #my_tuple[1] = 9 # Nhưng phần tử có index 3 trong tuple là list # list có thể thay đổi, nên phần tử đó có thể thay đổi # Output: (1, 3, 5, [8, 9]) my_tuple[3][0] = 8 print(my_tuple) # Nếu cần thay đổi tuple hãy gán lại giá trị cho nó # Output: ('q', 'u', 'a', 'n', 't', 'r', 'i', 'm', 'a', 'n', 'g') my_tuple = ('q', 'u', 'a', 'n', 't', 'r', 'i', 'm', 'a', 'n', 'g') print(my_tuple)
Bạn có thể dùng toán tử + để nối 2 tuple, toán tử * để lặp lại tuple theo số lần đã cho. Cả + và * đều cho kết quả là một tuple mới.
# Nối 2 tuple # Output: (2, 4, 6, 3, 5, 7) print((2, 4, 6) + (3, 5, 7)) # Lặp lại tuple # Output: ('TipsMake.com', 'TipsMake.com', 'TipsMake.com') print(("TipsMake.com",) * 3)
Xóa tuple
Các phần tử trong tuple không thể thay đổi nên chúng ta cũng không thể xóa, loại bỏ phần tử khỏi tuple. Nhưng việc xóa hoàn toàn một tuple có thể thực hiện được với từ khóa del như dưới đây:
QTM = ['q','u','a','n','t','r','i','m','a','n','g','.','c','o','m'] # Không thể xóa phần tử của tuple # Nếu bạn bỏ dấu # ở dòng 8, # sẽ tạo ra lỗi: # TypeError: 'tuple' object doesn't support item deletion #del QTM[3] # Có thể xóa toàn bộ tuple # Kết quả chạy code sẽ hiện ra lỗi: # NameError: name 'my_tuple' is not defined del QTM QTM
Phương thức và hàm dùng với tuple trong Python
Phương thức thêm phần tử và xóa phần tử không thể sử dụng với tuple, chỉ có 2 phương thức sau là dùng được:
- count(x) : Đếm số phần tử x trong tuple.
- index(x) : Trả về giá trị index của phần tử x đầu tiên mà nó gặp trong tuple.
QTM = ['q','u','a','n','t','r','i','m','a','n','g','.','c','o','m'] # Count # Output: 2 print(QTM.count('m')) # Index # Output: 3 print(QTM.index('n'))
Các hàm dùng trong tuple khá giống với list, gồm có:
- all() : Trả về giá trị True nếu tất cả các phần tử của tuple là true hoặc tuple rỗng.
- any() : Trả về True nếu bất kỳ phần tử nào của tuple là true, nếu tuple rỗng trả về False.
- enumerated() : Trả về đối tượng enumerate (liệt kê), chứa cặp index và giá trị của tất cả phần tử của tuple.
- len() : Trả về độ dài (số phần tử) của tuple.
- max() : Trả về phần tử lớn nhất của tuple.
- min() : Trả về phần tử nhỏ nhất của tuple.
- sorted() : Lấy phần tử trong tuple và trả về list mới được sắp xếp (tuple không sắp xếp được).
- sum() : Trả về tổng tất cả các phần tử trong tuple.
- tuple() : Chuyển đổi những đối tượng có thể lặp (list, string, set, dictionary) thành tuple.
Kiểm tra phần tử trong tuple
Bạn có thể kiểm tra xem một phần tử đã tồn tại trong tuple hay chưa với từ khóa in.
QTM = ['q','u','a','n','t','r','i','m','a','n','g','.','c','o','m'] # Kiểm tra phần tử # Output: True print('a' in QTM) # Output: False print('b' in QTM) # Not in operation # Output: False print('g' not in QTM)
Lặp qua các phần tử của tuple trong Python
Sử dụng vòng lặp for để lặp qua các phần tử trong tuple.
for ngon_ngu in ('Python','C++','Web'): print("Tôi thích lập trình",ngon_ngu)
Kết quả trả về sẽ như sau:
Tôi thích lập trình Python Tôi thích lập trình C++ Tôi thích lập trình Web
6. Set
Set trong Python là tập hợp các phần tử duy nhất, không có thứ tự. Các phần tử trong set phân cách nhau bằng dấu phẩy và nằm trong dấu ngoặc nhọn {}. Nhớ kỹ rằng các phần tử trong set không có thứ tự. Nhưng các phần tử trong set có thể thay đổi, có thể thêm hoặc xóa phần tử của set. Set có thể được sử dụng để thực hiện các phép toán như tập hợp, giao,.
Cách tạo set
Set được tạo bằng cách đặt tất cả các phần tử trong dấu ngoặc nhọn, phân tách bằng dấu phẩy hoặc sử dụng hàm set(). Set không giới hạn số lượng phần tử, nó có thể chứa nhiều kiểu biến khác nhau, nhưng không thể chứa phần tử có thể thay đổi được như list, set hay dictionary.
Ví dụ về set:
a = {5,2,3,1,4}
Nếu thực hiện lệnh in như sau:
print("a=", a)
You should read it
- For in Python loop
- More than 100 Python exercises have solutions (sample code)
- What is Python? Why choose Python?
- 5 choose the best Python IDE for you
- Bookmark 5 best Python programming learning websites
- How to set up Python to program on WSL
- Array in Python
- Why should you learn Python programming language?
- Multiple choice quiz about Python - Part 3
- Manage files and folders in Python
- How to install Python on Windows, macOS, Linux
- Python online editor
Maybe you are interested
This program will help you become invisible before the webcam lens is recording live Brain research explains the difference in the impact of technology on men and women 18 'extremely creative' inventions are available only in Japan 'Eyes glued' to the screen before going to bed is not harmful to the mental health of the bar, teenager! Can ants survive if they fall from the roof of the building? Discover the process of manufacturing terracotta army nearly 8,000 mysterious soldiers of Qin Shihuang