Python3 Basic Data Types
Variables in Python do not need to be declared. Every variable must be assigned a value before use; the variable is created only after the assignment.
In Python, a variable is just a variable and has no type; the type we speak of is the type of the object in memory that the variable refers to.
The equals sign = is used to assign a value to a variable. The left side is the variable name and the right side is the value stored in the variable. For example:
Example (Python 3.0+)
#!/usr/bin/python3
counter
=
100
Integer variable
miles
=
1000.0
Floating-point variable
name
=
"runoob"
String
(
counter
)
(
miles
)
(
name
)
Run Example »
Running the program above produces the following output:
100
1000.0
runoob
Assigning multiple variables
Python allows you to assign values to multiple variables at the same time. For example:
a = b = c = 1
The example above creates an integer object with value 1, and three variables are given the same value.
You can also assign different values to multiple variables at once. For example:
a, b, c = 1, 2, "runoob"
In the example above, the integer objects 1 and 2 are assigned to variables a and b, and the string object "runoob" is assigned to variable c.
You can check a variable's type with the type() function:
Example
Variable definition
x
=
10
Integers
y
=
3.14
Float (floating point number)
name
=
"Alice"
String
is_active
=
True
Boolean
Multiple variable assignment
a
,
b
,
c
=
1
,
2
,
"three"
Check the data type
(
type
(
x
)
)
(
type
(
y
)
)
(
type
(
name
)
)
(
type
(
is_active
)
)
Standard data types
Python3 has 6 standard data types plus the bool type (bool is a subclass of int and is sometimes listed separately):
- Number
- String
- bool
- List
- Tuple
- Set
- Dictionary
By mutability, they can be divided into the following two groups:
- **Immutable data (4):** Number, String, bool, Tuple
- **Mutable data (3):** List, Dictionary, Set
There are also some advanced data types, such as the byte array type bytes.
Number
Python3 supports int, float, bool, complex。
In Python 3 there is only one integer type, int, represented as a long integer; there is no Long as in Python 2.
The built-in type() function can be used to query the type of the object a variable refers to.
>>> a, b, c, d = 20, 5.5, True, 4+3j
>>> print(type(a), type(b), type(c), type(d))
You can also use isinstance() to check:
Example
a
=
111
isinstance
(
a
,
int
)
True
isinstance and type The difference between them is:
type()does not consider a subclass to be of its parent class type.isinstance()considers a subclass to be of its parent class type.
>>> class A:
... pass
...
>>> class B(A):
... pass
...
>>> isinstance(A(), A)
True
>>> type(A()) == A
True
>>> isinstance(B(), A)
True
>>> type(B()) == A
False
Note:In Python3, bool is a subclass of int, and True and False can be added to numbers,True==1、False==0 returns True, but you can use is to check object identity.
>>> issubclass(bool, int) True >>> True == 1 True >>> False == 0 True >>> True + 1 2 >>> False + 1 1 >>> 1 is True
Why does a SyntaxWarning appear?
Python detects that you are using is to compare a literal integer (such as 1) with True, which is usually a coding error - because is compares object identity (whether they are the same object), not value equality. Python recommends using == to compare values, unless you really need to check whether they are the same object.
In Python 2 there was no boolean type; it used the number 0 to represent False and 1 to represent True.
When you assign a value, a Number object is created:
var1 = 1
var2 = 10
You can delete an object reference with the del statement:
del var1[, var2[, var3[...., varN]]]
For example:
del var
del var_a, var_b
Numeric operations
Example
5
4
Addition
9
4.3
2
Subtraction
2.3
3
7
Multiplication
21
2
/
4
Division, produces a float
0.5
2
//
4
Floor division, produces an integer
0
17
%
3
Remainder
2
2
**
5
Exponentiation
32
Note:
- Python can assign values to multiple variables at once, such as
a, b = 1, 2。 - A variable can be made to point to objects of different types through assignment.
- Numeric division has two operators: / returns a float, and // returns an integer (rounded down).
- In mixed calculations, Python automatically converts integers to floats.
Numeric type examples
| int | float | complex |
|---|---|---|
| 10 | 0.0 | 3.14j |
| 100 | 15.20 | 45.j |
| -786 | -21.9 | 9.322e-36j |
| 0o17 | 32.3e+18 | .876j |
| -0o112 | -90. | -.6545+0J |
| -0x260 | -32.54e100 | 3e+26J |
| 0x69 | 70.2E-12 | 4.53e-7j |
Note: in Python 3, integer literals cannot have leading zeros (such as
080); octal numbers must use the0oprefix (such as0o17), hexadecimal uses0xprefix (such as0x69), and binary uses0bprefix.
Python also supports complex numbers, which consist of a real part and an imaginary part and can be written as a + bj or complex(a, b); the real part a and imaginary part b are both floats.
String
Strings in Python are enclosed in single quotes ' or double quotes ", and a backslash is used to escape special characters.
The syntax for string slicing is as follows:
变量[头下标:尾下标]
Index values start at 0, with -1 being the position starting from the end.
The plus sign + is the string concatenation operator, and the asterisk * means repeating the current string, with the number combined with it giving the repeat count. Example:
Example
#!/usr/bin/python3
my_str
=
'Runoob'
Define a string variable (avoid using str as a variable name, as it shadows the built-in type)
(
my_str
)
Print the whole string: Runoob
(
my_str
[
0
:-
1
]
)
Print index 0 up to the second-to-last character (excluding the last): Runoo
(
my_str
[
0
]
)
Print the first character: R
(
my_str
[
2
:
5
]
)
Print characters at indexes 2, 3, 4 (excluding index 5): noo
(
my_str
[
2
:
]
)
Print from index 2 to the end: noob
(
my_str *
2
)
Print twice: RunoobRunoob
(
my_str +
"TEST"
)
String concatenation: RunoobTEST
Running the program above produces the following output:
Runoob
Runoo
R
noo
noob
RunoobRunoob
RunoobTEST
Python uses a backslash to escape special characters; if you do not want the backslash to escape, add an r before the string to make it a raw string:
Example
(
'Ru\noob'
)
Ru
oob
(
r
'Ru\noob'
)
Ru\noob
In addition, a backslash can act as a line continuation character, meaning the next line continues the previous one. You can also use """...""" or '''...''' to span multiple lines.
Note that Python has no separate character type; a character is a string of length 1.
Example
word
=
'Python'
(
word
[
0
]
,
word
[
5
]
)
P n
(
word
[
1
]
,
word
[
6
]
)
n P
Unlike C strings, Python strings cannot be changed. Assigning to an index position, such as word[0] = 'm', causes an error.
Note:
- A backslash can be used for escaping; use the
rprefix to prevent the backslash from escaping (a raw string). - Strings can be joined with the
+operator and repeated with the*operator. - Strings in Python have two indexing directions: from left to right starting at 0, and from right to left starting at -1.
- Strings in Python cannot be changed; strings are an immutable type.
bool
The boolean type is either True or False. In Python, True and False are keywords representing boolean values.
The boolean type can control program flow, such as checking whether a condition holds, or executing a block of code when a condition is satisfied.
Characteristics of the boolean type:
- The boolean type has only two values: True and False.
- bool is a subclass of int, so boolean values can be treated as integers, where True is equivalent to 1 and False to 0.
- The boolean type can be compared with other data types such as numbers and strings. When comparing, Python treats True as 1 and False as 0.
- The boolean type can be used with logical operators, including
and、orandnot, to combine multiple boolean expressions. - Boolean values can also be converted to other data types such as integers, floats, and strings. In the conversion, True becomes 1 and False becomes 0.
- You can use the
bool()The function converts values of other types to booleans. The following values convert toFalse:None、False, zero (0、0.0、0j), empty sequences (such as''、()、[]) and empty mappings (such as{}). All other values convert toTrue。
Example
Boolean values and types
a
=
True
b
=
False
(
type
(
a
)
)
(
type
(
b
)
)
Integer behavior of the boolean type
(
int
(
True
)
)
1
(
int
(
False
)
)
0
Conversion with the bool() function
(
bool
(
0
)
)
False
(
bool
(
42
)
)
True
(
bool
(
''
)
)
False
(
bool
(
'Python'
)
)
True
(
bool
(
[
]
)
)
False
(
bool
(
[
1
,
2
,
3
]
)
)
True
Boolean logical operations
(
True
and
False
)
False
(
True
or
False
)
True
(
not
True
)
False
Boolean comparison operations
(
5
3
)
True
(
2
==
2
)
True
(
7
<
4
)
False
Boolean values in control flow
if
True
:
(
"This will always print"
)
if
not
False
:
(
"This will also always print"
)
x
=
10
if
x:
(
"x is a nonzero value and is True in a boolean context"
)
**Note:** in Python, all nonzero numbers and non-empty strings, lists, tuples, and other data types are treated as True; only 0, empty strings, empty lists, empty tuplesand similar are treated as False. Therefore, when converting to a boolean, pay attention to the truthiness of the data type.
List
List is the most frequently used data type in Python.
Lists can implement most collection-class data structures. Elements in a list can be of different types; they support numbers, strings, and can even contain lists (i.e. nested lists).
A list is written between square brackets [] as a comma-separated list of elements.
Like strings, lists can be indexed and sliced; slicing a list returns a new list containing the required elements.
The syntax for list slicing is as follows:
变量[头下标:尾下标]
Index values start at 0, with -1 being the position starting from the end.

The plus sign + is the list concatenation operator, and the asterisk * is the repetition operation. Example:
Example
#!/usr/bin/python3
my_list
=
[
'abcd'
,
786
,
2.23
,
'runoob'
,
70.2
]
Avoid using list as a variable name, as it shadows the built-in type
tinylist
=
[
123
,
'runoob'
]
(
my_list
)
Print the whole list: ['abcd', 786, 2.23, 'runoob', 70.2]
(
my_list
[
0
]
)
Print the first element (index 0): abcd
(
my_list
[
1
:
3
]
)
Print elements at indexes 1 and 2 (excluding index 3): [786, 2.23]
(
my_list
[
2
:
]
)
Print all elements from index 2 to the end: [2.23, 'runoob', 70.2]
(
tinylist *
2
)
Print tinylist twice: [123, 'runoob', 123, 'runoob']
(
my_list + tinylist
)
Concatenate two lists
The example above produces the following output:
['abcd', 786, 2.23, 'runoob', 70.2]
abcd
[786, 2.23]
[2.23, 'runoob', 70.2]
[123, 'runoob', 123, 'runoob']
['abcd', 786, 2.23, 'runoob', 70.2, 123, 'runoob']
Unlike Python strings, elements in a list can be changed:
Example
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
]
=
[
]
Set the corresponding element values to an empty list, i.e. delete those elements
a
[
9
,
2
,
6
]
List has many built-in methods, such as append()、pop() and so on, which will be covered later.
Note:
- A list is written between square brackets, with elements separated by commas.
- Like strings, lists can be indexed and sliced.
- Lists can be concatenated with the + operator.
- Elements in a list can be changed (mutable type).
Python list slicing accepts a third argument that sets the step size; the following example sets step 2 at indexes 1 to 4 (taking every other element):

If the third argument is negative, it reads backwards; the following example reverses the word order in a string:
Example
def
reverseWords
(
input
)
:
Split the string on spaces, turning each word into a list element
inputWords
=
input
.
split
(
" "
)
The three arguments of inputWords[-1::-1]:
The first argument -1 means start from the last element
The second argument is empty, meaning move to the beginning of the list
The third argument -1 means a reverse step (move one position to the left each time)
inputWords
=
inputWords
[
1
::-
1
]
Join the words back together with spaces
output
=
' '
.
join
(
inputWords
)
return
output
if
name
==
"main"
:
input
=
'I like runoob'
rw
=
reverseWords
(
input
)
(
rw
)
The output is:
runoob like I
Tuple
A tuple is similar to a list, except that its elements cannot be modified. Tuples are written in parentheses () with elements separated by commas.
Elements in a tuple can also be of different types:
Example
#!/usr/bin/python3
my_tuple
=
(
'abcd'
,
786
,
2.23
,
'runoob'
,
70.2
)
Avoid using tuple as a variable name
tinytuple
=
(
123
,
'runoob'
)
(
my_tuple
)
Output the complete tuple
(
my_tuple
[
0
]
)
Output the first element: abcd
(
my_tuple
[
1
:
3
]
)
Output elements at indexes 1 and 2: (786, 2.23)
(
my_tuple
[
2
:
]
)
Output all elements from index 2
(
tinytuple *
2
)
Output tinytuple twice
(
my_tuple + tinytuple
)
Concatenate two tuples
The example above produces the following output:
('abcd', 786, 2.23, 'runoob', 70.2)
abcd
(786, 2.23)
(2.23, 'runoob', 70.2)
(123, 'runoob', 123, 'runoob')
('abcd', 786, 2.23, 'runoob', 70.2, 123, 'runoob')
Tuples, like strings, can be indexed with subscripts starting at 0, with -1 as the position starting from the end, and can also be sliced.
In fact, a string can be viewed as a special kind of tuple.
Example
tup
=
(
1
,
2
,
3
,
4
,
5
,
6
)
(
tup
[
0
]
)
1
(
tup
[
1
:
5
]
)
(
2
,
3
,
4
,
5
)
tup
[
0
]
=
11
Modifying a tuple's elements is illegal
Traceback
(
most recent call last
)
:
File
"
,
line
1
,
in
<
;
module>
;
TypeError
:
'tuple'
object
does
not
support item assignment
Although a tuple's elements cannot be changed, it can contain mutable objects such as lists.
Constructing tuples with 0 or 1 element is special and has some extra syntax rules:
tup1 = () # 空元组
tup2 = (20,) # 一个元素,需要在元素后添加逗号
If you want to create a tuple with a single element, add a comma after the element to distinguish it from a plain value, because without the comma Python interprets the parentheses as those used in mathematical expressions:
not_a_tuple = (42) # 这是整数 42,不是元组
string、list and tuple all belong to sequence types.
Note:
- Like strings, tuple elements cannot be modified (immutable type).
- Tuples can also be indexed and sliced in the same way as lists.
- Note the special syntax rules for constructing tuples with 0 or 1 element.
- Tuples can also be concatenated with the + operator.
Set
A Set in Python is an unordered, mutable data type used to store unique elements. Elements in a set do not repeat, and common set operations such as intersection, union, and difference are supported.
In Python, sets use braces {} with elements separated by commas, and can also be created with the set() function.
Note:An empty set must be created with set() instead of {}, because {} creates an empty dictionary.
Creation format:
parame = {value01, value02, ...}
或者
set(value)
Example
#!/usr/bin/python3
sites
=
{
'Google'
,
'Taobao'
,
'Runoob'
,
'Facebook'
,
'Zhihu'
,
'Baidu'
}
(
sites
)
Output the set (unordered, duplicate elements are removed automatically)
Membership test
if
'Runoob'
in
sites:
(
'Runoob is in the set'
)
else
:
(
'Runoob is not in the set'
)
Sets support set operations
a
=
set
(
'abracadabra'
)
b
=
set
(
'alacazam'
)
(
a
)
Unique characters in a
(
a - b
)
Difference of a and b (in a but not in b)
(
a | b
)
Union of a and b (in a or in b)
(
a & b
)
Intersection of a and b (in both a and b)
(
a ^ b
)
Symmetric difference of a and b (in a or b, but not both)
The example above produces the following output:
{'Zhihu', 'Baidu', 'Taobao', 'Runoob', 'Google', 'Facebook'}
Runoob 在集合中
{'b', 'c', 'a', 'r', 'd'}
{'r', 'b', 'd'}
{'b', 'c', 'a', 'z', 'm', 'r', 'l', 'd'}
{'c', 'a'}
{'z', 'b', 'm', 'r', 'l', 'd'}
Dictionary
A dictionary is another very useful built-in data type in Python.
A dictionary is a mapping type identified by {}, and it is a collection of key : value pairs. Keys must be of an immutable type and must be unique within the same dictionary.
Note:Starting with Python 3.7, dictionaries preserve theinsertion orderof elements and are no longer unordered. If you need the features of an ordered dictionary, just use a plain
dict.
Example
#!/usr/bin/python3
my_dict
=
{
}
my_dict
[
'one'
]
=
"1 - Runoob Tutorial"
my_dict
[
2
]
=
"2 - Runoob Tools"
tinydict
=
{
'name'
:
'runoob'
,
'code'
:
1
,
'site'
:
'www.runoob.com'
}
(
my_dict
[
'one'
]
)
Output the value of key 'one'
(
my_dict
[
2
]
)
Output the value of key 2
(
tinydict
)
Output the complete dictionary
(
tinydict.
keys
(
)
)
Output all keys
(
tinydict.
values
(
)
)
Output all values
The example above produces the following output:
1 - Runoob Tutorial
2 - 菜鸟工具
{'name': 'runoob', 'code': 1, 'site': 'www.runoob.com'}
dict_keys(['name', 'code', 'site'])
dict_values(['runoob', 1, 'www.runoob.com'])
constructor dict() A dictionary can be built directly from a sequence of key/value pairs:
Example
dict
(
[
(
'Runoob'
,
1
)
,
(
'Google'
,
2
)
,
(
'Taobao'
,
3
)
]
)
{
'Runoob'
:
1
,
'Google'
:
2
,
'Taobao'
:
3
}
{
x: x**
2
for
x
in
(
2
,
4
,
6
)
}
{
2
:
4
,
4
:
16
,
6
:
36
}
dict
(
Runoob
=
1
,
=
2
,
Taobao
=
3
)
{
'Runoob'
:
1
,
'Google'
:
2
,
'Taobao'
:
3
}
{x: x**2 for x in (2, 4, 6)} uses a dictionary comprehension; for more on comprehensions see:Python Comprehensions。
In addition, the dictionary type has some built-in functions, such as clear()、keys()、values() , etc.
Note:
- A dictionary is a mapping type whose elements are key/value pairs.
- Dictionary keys must be of an immutable type and cannot repeat.
- Create an empty dictionary with {}。
- Starting with Python 3.7, dictionaries preserve insertion order.
The bytes type
In Python3, the bytes type represents an immutable binary sequence. Unlike strings, elements of bytes are integer values (integers between 0 and 255), not Unicode characters.
The bytes type is typically used to handle binary data such as image, audio, and video files. In network programming, bytes are also commonly used to transmit binary data.
The most common way to create a bytes object is with the b prefix:
Example
x
=
b
"hello"
Create a bytes object with the b prefix
(
x
)
b'hello'
(
type
(
x
)
)
(
x
[
0
]
)
104 (the ASCII value of 'h'; bytes elements are integers)
You can also use bytes() The function converts objects of other types to bytes; the second argument specifies the encoding:
x = bytes("hello", encoding="utf-8")
Like strings, bytes supports slicing, concatenation, searching, replacement, and other operations. Because bytes is immutable, modifying it requires creating a new bytes object:
Example
x
=
b
"hello"
y
=
x
[
1
:
3
]
Slicing, yielding b'el'
z
=
x + b
"world"
Concatenation, yielding b'helloworld'
(
y
)
b'el'
(
z
)
b'helloworld'
Note that bytes elements are integer values, so comparisons must use the corresponding integer values. You can use the ord() function to convert a character to its integer value:
Example
x
=
b
"hello"
if
x
[
0
]
==
ord
(
"h"
)
:
ord("h") returns 104
(
"The first element is 'h'"
)
Python data type conversion
Sometimes we need to convert built-in data types; simply use the data type as a function name. In the next chapter Python3 Data Type Conversion it is explained in detail.
The following built-in functions perform conversions between data types; they return a new object representing the converted value:
| function | Description |
|---|---|
|
Convert x to an integer |
|
|
Convert x to a float |
|
|
Create a complex number |
|
|
Convert object x to a string |
|
|
Convert object x to an expression string |
|
|
Evaluate a valid Python expression in a string and return an object |
|
|
Convert sequence s to a tuple |
|
|
Convert sequence s to a list |
|
|
Convert to a mutable set |
|
|
Create a dictionary. d must be a sequence of (key, value) tuples. |
|
|
Convert to an immutable set |
|
|
Convert an integer to the corresponding character |
|
|
Convert a character to its integer value (Unicode code point) |
|
|
Convert an integer to a hexadecimal string |
|
|
Convert an integer to an octal string |