An overview of basic data types based on Python3

  • 2020-04-02 13:55:10
  • OfStack

This article introduces the basic data types in Python3, which is a must for beginners to learn, as follows:

First of all, Variables in Python do not need to be declared. Each variable must be assigned a value before it is used, and the variable is not created until it is assigned a value . In Python, a variable is a variable. It has no type. There are six standard data types in Python 3:

Numbers (Numbers)

String

List

Tuple.

Sets (Sets)

Dictionaries (dictionary)

This article mainly introduces the definition of these data types and their relations and differences.

One, the Numbers

Python 3 supports int, float, bool, complex Numbers. The assignment and computation of numeric types is straightforward, as is the case in most languages. The built-in type() function can be used to query the object type referred to by the variable.


>>> a, b, c, d = 20, 5.5, True, 4+3j
>>> print(type(a), type(b), type(c), type(d))
<class 'int'> <class 'float'> <class 'bool'> <class 'complex'>

Numerical operation:


>>> 5 + 4 #  add 
9
>>> 4.3 - 2 #  subtraction 
2.3
>>> 3 * 7 #  The multiplication 
21
>>> 2 / 4 #  Divide, you get a float 
0.5
>>> 2 //Divide by 4, you get an integer
0
>>> 17 % 3 #  Take more than  
2
>>> 2 ** 5 #  chengfang 
32

Key points:

1. Python can assign values to multiple variables at the same time, such as a, b = 1, 2.
2. A variable can be assigned to different types of objects.
Division of a number (/) always returns a floating point number. To get an integer, use the // operator.
4. In hybrid calculations, Pyhton converts integers to floating point Numbers.

Second, the Strings

The string STR in Python is enclosed in single quotes (' ') or double quotes (" "), with a backslash (\) escaping the special character.


>>> s = 'Yes,he doesn't'
>>> print(s, type(s), len(s))
Yes,he doesn't <class 'str'> 14

If you don't want the backslash to escape, you can put an r in front of the string to indicate the original string:


>>> print('C:somename')
C:some
ame
>>> print(r'C:somename')
C:somename

In addition, a backslash can be used as a line continuation to indicate that the next line is a continuation of the previous line. You can also use """..." "" or" '... "" spans many lines.

Strings can be concatenated using the + operator string, or repeated using the * operator:


>>> print('str'+'ing', 'my'*3)
string mymymy

There are two ways to index a string in Python. The second one goes from right to left, and then goes down from minus 1. Note that there is no single character type; a character is a string of length 1.


>>> word = 'Python'
>>> print(word[0], word[5])
P n
>>> print(word[-1], word[-6])
n P

You can also slice a string to get a substring. Separate the two indexes with a colon in the form of a variable [header subscript: tail subscript]. The scope of interception is closed and open, and both indexes can be omitted:


>>> word = 'ilovepython'
>>> word[1:5]
'love'
>>> word[:]
'ilovepython'
>>> word[5:]
'python'
>>> word[-10:-6]
'love'

Unlike C strings, Python strings cannot be changed. Assigning a value to an index location, such as word[0] = 'm', causes an error.

Key points:

1, backslashes can be used to escape, using r can not escape backslashes.
2. Strings can be concatenated with the + operator and repeated with the * operator.
3. Strings in Python are indexed in two ways, starting with 0 from left to right and -1 from right to left.
4. Strings cannot be changed in Python.

Third, the List

List is the most frequently used data type in Python. A list is a comma-separated list of elements written between square brackets. The types of elements in the list can be different:


>>> a = ['him', 25, 100, 'her'] 
>>> print(a, type(a), len(a))
['him', 25, 100, 'her'] <class 'list'> 4

Like strings, lists can also be indexed and sliced, and a new list containing the required elements is returned when the list is sliced. The details are not detailed here.

The list also supports concatenation operations, using the + operator:


>>> a = [1, 2, 3, 4, 5]
>>> a + [6, 7, 8]
[1, 2, 3, 4, 5, 6, 7, 8]

Unlike Python strings, the elements in a list can be changed:


>>> a = [1, 2, 3, 4, 5, 6]
>>> a[0] = 9
>>> a[2:5] = [13, 14, 15]
>>> a
[9, 2, 13, 14, 15, 6]
>>> a[2:5] = []  #  delete 
>>> a
[9, 2, 6]

There are many methods built into the List, such as append(), pop(), and so on, which will be covered later.

Key points:

1. List is written between square brackets and the elements are separated by commas.
2. Like strings, lists can be indexed and sliced.
3. The List can be spliced using the + operator.
4. The elements in the List can be changed.

Fourth, the Tuple

Tuples are similar to lists, except that the elements of a tuple cannot be modified. A tuple is a comma-separated list of elements written between parentheses. Element types in tuples can also be different:


>>> a = (1991, 2014, 'physics', 'math')
>>> print(a, type(a), len(a))
(1991, 2014, 'physics', 'math') <class 'tuple'> 4

Tuples are similar to strings in that they can be indexed and indexed starting at 0, or they can be truncated/sliced (see above, no more here). Instead, think of a string as a special tuple.


>>> tup = (1, 2, 3, 4, 5, 6)
>>> print(tup[0], tup[1:5])
1 (2, 3, 4, 5)
>>> tup[0] = 11 #  Modifying tuple elements is illegal 

While the elements of a tuple are immutable, it can contain mutable objects, such as a list list.
Constructing a tuple with 0 or 1 elements is a special problem, so there are some additional syntax rules:


tup1 = () #  An empty tuple 
tup2 = (20,) #  An element that needs to be followed by a comma 

In addition, tuples also support the + operator:


>>> tup1, tup2 = (1, 2, 3), (4, 5, 6)
>>> print(tup1+tup2)
(1, 2, 3, 4, 5, 6)

Strings, lists, and tuples all belong to sequences.

Key points:

1. Like strings, elements of tuples cannot be modified.
Tuples can also be indexed and sliced in the same way.
3. Notice the special syntax for constructing tuples with 0 or 1 elements.
4. Tuples can also be spliced using the + operator.

Fifth, Sets.

A set is a set of unordered elements that do not repeat. The basic functionality is to do membership testing and eliminate duplicate elements. You can create set sets using curly braces or the set() function. Note: to create an empty set, you must use set() instead of {}, because {} is used to create an empty dictionary.


>>> student = {'Tom', 'Jim', 'Mary', 'Tom', 'Jack', 'Rose'}
>>> print(student)  #  Duplicate elements are automatically removed 
{'Jim', 'Jack', 'Mary', 'Tom', 'Rose'}
>>> 'Rose' in student # membership testing (member testing) 
True
>>> # set You can do set operations 
... 
>>> a = set('abracadabra')
>>> b = set('alacazam')
>>> a
{'a', 'b', 'c', 'd', 'r'}
>>> a - b   # a and b The difference between the set 
{'b', 'd', 'r'}
>>> a | b   # a and b And set 
{'l', 'm', 'a', 'b', 'c', 'd', 'z', 'r'}
>>> a & b   # a and b The intersection of 
{'a', 'c'}
>>> a ^ b   # a and b An element that does not exist at the same time 
{'l', 'm', 'b', 'd', 'z', 'r'}

Key points:

1. Elements in a set are not repeated; if repeated, they are automatically removed.
A set set can be created with braces or a set() function, but an empty set must be created with a set() function.
3. Set sets can be used to test members and eliminate duplicate elements.

Six, Dictionaries

Dictionaries are another very useful built-in data type in Python. A dictionary is a mapping type, which is an unordered set of key: value pairs. Keywords must be immutable, meaning that lists and tuples containing mutable types cannot be keywords. In the same dictionary, the keywords must be different.


>>> dic = {} #  Create an empty dictionary 
>>> tel = {'Jack':1557, 'Tom':1320, 'Rose':1886}
>>> tel
{'Tom': 1320, 'Jack': 1557, 'Rose': 1886}
>>> tel['Jack']  #  Main operation: pass key The query 
1557
>>> del tel['Rose'] #  Delete a key-value pair 
>>> tel['Mary'] = 4127 #  Add a key-value pair 
>>> tel
{'Tom': 1320, 'Jack': 1557, 'Mary': 4127}
>>> list(tel.keys()) #  Returns all key Consisting of a list
['Tom', 'Jack', 'Mary']
>>> sorted(tel.keys()) #  According to the key The sorting 
['Jack', 'Mary', 'Tom']
>>> 'Tom' in tel    #  Members of the test 
True
>>> 'Mary' not in tel #  Members of the test 
False

The constructor dict() builds the dictionary directly from the sequence of key-value pairs, which can also be derived, as follows:


>>> dict([('sape', 4139), ('guido', 4127), ('jack', 4098)])
{'jack': 4098, 'sape': 4139, 'guido': 4127}

>>> {x: x**2 for x in (2, 4, 6)}
{2: 4, 4: 16, 6: 36}

>>> dict(sape=4139, guido=4127, jack=4098)
{'jack': 4098, 'sape': 4139, 'guido': 4127}

There are also built-in functions for dictionary types, such as clear(), keys(), values(), and so on.

Key points:

1. A dictionary is a mapping type whose elements are key-value pairs.
2. The keywords in the dictionary must be immutable and cannot be repeated.
3. Use {} to create an empty dictionary.


Related articles: