Python3 Basic Data Types
Variables in Python do not need to be declared. Each variable must be assigned a value before use, and the variable is created only after assignment.
In Python, a variable is just a variable; it has no type. What we refer to as “type” is the type of the object in memory that the variable points to.
The equals sign = is used to assign values to variables. The left side of the equals sign is the variable name, and the right side is the value stored in the variable. For example:
Example (Python 3.0+)
Section titled “Example (Python 3.0+)”Running the above program produces the following output:
Assigning Multiple Variables
Section titled “Assigning Multiple Variables”Python allows you to assign values to multiple variables simultaneously. For example:
The above example creates an integer object with the value 1, and three variables are assigned the same value.
You can also assign different values to multiple variables simultaneously. For example:
In the above example, the integer objects 1 and 2 are assigned to variables a and b respectively, and the string object “runoob” is assigned to variable c.
You can check the type of a variable using the type() function:
Example
Section titled “Example”Standard Data Types
Section titled “Standard Data Types”Python3 has 6 standard data types, plus the bool type (bool is a subclass of int, sometimes listed separately):
- Number
- String
- bool (Boolean)
- List
- Tuple
- Set
- Dictionary
Based on whether they are mutable, they can be divided into two categories:
- Immutable data (4 types): Number, String, bool, Tuple
- Mutable data (3 types): List, Dictionary, Set
Additionally, there are some advanced data types, such as the bytes type.
Number
Section titled “Number”Python3 supports int, float, bool, complex.
In Python 3, there is only one integer type int, represented as long integers, without the Long type from Python 2.
The built-in type() function can be used to query the type of the object a variable points to.
Additionally, you can use isinstance() to check:
Example
Section titled “Example”The difference between isinstance and type is:
type()does not consider a subclass as a parent class type.isinstance()considers a subclass as a parent class type.
Note: In Python3,
boolis a subclass ofint.TrueandFalsecan be added to numbers.True==1andFalse==0will return True, but you can useisto check object identity.Why does SyntaxWarning appear?
Python detects that you are using
isto compare a literal integer (like 1) withTrue, which is usually a code error — becauseiscompares object identity (whether they are the same object), not whether the values are equal. 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 0 for False and 1 for True.
When you specify a value, a Number object is created:
You can use the del statement to delete object references:
For example:
Numeric Operations
Section titled “Numeric Operations”Example
Section titled “Example”Note:
- Python can assign values to multiple variables simultaneously, e.g.,
a, b = 1, 2. - A variable can point to objects of different types through assignment.
- Numeric division includes two operators:
/returns a float,//returns an integer (rounded down). - In mixed calculations, Python automatically converts integers to floats.
Numeric Type Examples
Section titled “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: Python 3 does not allow leading zeros in integer literals (like
080). Octal numbers must use the0oprefix (e.g.,0o17), hexadecimal uses the0xprefix (e.g.,0x69), and binary uses the0bprefix.
Python also supports complex numbers. Complex numbers consist of a real part and an imaginary part, expressed as a + bj or complex(a, b). Both the real part a and the imaginary part b are floats.
String
Section titled “String”In Python, strings are enclosed in single quotes ' or double quotes ", and the backslash \\ is used to escape special characters.
The syntax for string slicing is:
Index values start at 0, with -1 representing the position from the end.
The plus sign + is the string concatenation operator, and the asterisk * repeats the current string, with the number indicating the number of repetitions. Example:
Example
Section titled “Example”Running the above program produces the following output:
Python uses the backslash \\ to escape special characters. If you don’t want the backslash to escape, you can add an r before the string to create a raw string:
Example
Section titled “Example”Additionally, the backslash \\ can be used as a line continuation character, indicating that the next line is a continuation of the current line. You can also use """...""" or '''...''' to span multiple lines.
Note that Python does not have a separate character type; a single character is simply a string of length 1.
Example
Section titled “Example”Unlike C strings, Python strings cannot be changed. Assigning a value to an index position, such as word[0] = 'm', will cause an error.
Note:
- Backslash can be used for escaping. Using the
rprefix prevents backslash escaping (raw string). - Strings can be concatenated with the
+operator and repeated with the*operator. - Python strings have two indexing methods: from left to right starting at 0, and from right to left starting at -1.
- Python strings cannot be changed; strings are immutable types.
bool (Boolean)
Section titled “bool (Boolean)”The boolean type is either True or False. In Python, True and False are both keywords that represent boolean values.
Boolean types can be used to control the flow of a program, such as determining whether a condition holds or executing a block of code when a condition is satisfied.
Boolean type characteristics:
- The boolean type has only two values:
TrueandFalse. boolis a subclass ofint, so boolean values can be used as integers, whereTrueis equivalent to 1 andFalseis equivalent to 0.- Boolean types can be compared with other data types, such as numbers, strings, etc. When comparing, Python treats
Trueas 1 andFalseas 0. - Boolean types can be used with logical operators, including
and,or, andnot, to combine multiple boolean expressions. - Boolean types can also be converted to other data types, such as integers, floats, and strings. When converting,
Trueis converted to 1 andFalseis converted to 0. - You can use the
bool()function to convert values of other types to boolean values. The following values areFalsewhen converted to boolean:None,False, zero (0,0.0,0j), empty sequences (like'',(),[]), and empty mappings (like{}). All other values areTruewhen converted to boolean.
Example
Section titled “Example”Note: In Python, all non-zero numbers and non-empty strings, lists, tuples, and other data types are treated as True. Only 0, empty strings, empty lists, empty tuples, etc., are treated as False. Therefore, when performing boolean type conversion, pay attention to the truthiness of the data type.
List is the most frequently used data type in Python.
Lists can implement most collection data structures. The types of elements in a list can be different; it supports numbers, strings, and can even contain lists (nested lists).
Lists are written within square brackets [], with elements separated by commas.
Like strings, lists can also be indexed and sliced. Slicing a list returns a new list containing the required elements.
The syntax for list slicing is:
Index values start at 0, with -1 representing the position from the end.

The plus sign + is the list concatenation operator, and the asterisk * is the repetition operator. Example:
Example
Section titled “Example”The above example outputs:
Unlike Python strings, elements in a list can be changed:
Example
Section titled “Example”List has many built-in methods, such as append(), pop(), etc., which will be discussed later.
Note:
- Lists are written within square brackets, with elements separated by commas.
- Like strings, lists can be indexed and sliced.
- Lists can be concatenated using the
+operator. - Elements in a list can be changed (mutable type).
Python list slicing can accept a third parameter, which specifies the step size. The following example slices the list from index 1 to index 4 with a step size of 2 (taking every other element):

If the third parameter is negative, it indicates reverse traversal. The following example is used to reverse the order of words in a string:
Example
Section titled “Example”The output is:
Tuples are similar to lists, except that the elements of a tuple cannot be modified. Tuples are written within parentheses (), with elements separated by commas.
The element types in a tuple can also be different:
Example
Section titled “Example”The above example outputs:
Tuples are similar to strings: they can be indexed starting from 0, with -1 representing the position from the end, and can also be sliced.
In fact, strings can be viewed as a special kind of tuple.
Example
Section titled “Example”Although the elements of a tuple cannot be changed, it can contain mutable objects, such as lists.
Constructing tuples with 0 or 1 element is special and has some additional syntax rules:
If you want to create a tuple with only one element, you must add a comma after the element to distinguish it from a plain value. Without the comma, Python interprets the parentheses as mathematical grouping parentheses:
string, list, and tuple all belong to sequence types.
Note:
- Like strings, the elements of a tuple cannot be modified (immutable type).
- Tuples can also be indexed and sliced, in the same way as lists.
- Pay attention to the special syntax rules for constructing tuples with 0 or 1 element.
- Tuples can also be concatenated using the
+operator.
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 can be performed.
In Python, sets are represented using curly braces {}, with elements separated by commas ,. You can also use the set() function to create a set.
Note: To create an empty set, you must use
set()instead of{}, because{}creates an empty dictionary.
Creation format:
Example
Section titled “Example”The above example outputs:
Dictionary
Section titled “Dictionary”Dictionary is another very useful built-in data type in Python.
A dictionary is a mapping type, identified by {}. It is a collection of key: value pairs. Keys must be of immutable types and must be unique within the same dictionary.
Note: Starting from Python 3.7, dictionaries maintain the insertion order of elements and are no longer unordered. If you need ordered dictionary behavior, simply use a regular
dict.
Example
Section titled “Example”The above example outputs:
The dict() constructor can build a dictionary directly from a sequence of key-value pairs:
Example
Section titled “Example”{x: x**2 for x in (2, 4, 6)} uses dictionary comprehension. For more on comprehensions, see: Python Comprehensions.
Additionally, dictionary types have some built-in functions, such as clear(), keys(), values(), etc.
Note:
- A dictionary is a mapping type; its elements are key-value pairs.
- Dictionary keys must be of immutable types and cannot be duplicated.
- Use {} to create an empty dictionary.
- Starting from Python 3.7, dictionaries maintain insertion order.
bytes Type
Section titled “bytes Type”In Python3, the bytes type represents an immutable binary sequence (byte sequence). Unlike the string type, elements in the bytes type are integer values (integers between 0 and 255), not Unicode characters.
The bytes type is typically used for handling binary data, such as image files, audio files, video files, etc. In network programming, the bytes type is also frequently used to transmit binary data.
The most common way to create a bytes object is by using the b prefix:
Example
Section titled “Example”You can also use the bytes() function to convert other types of objects to bytes type. The second parameter specifies the encoding method:
Like the string type, the bytes type also supports operations such as slicing, concatenation, searching, and replacement. Since the bytes type is immutable, modification operations require creating a new bytes object:
Example
Section titled “Example”Note that elements in the bytes type are integer values, so when performing comparison operations, you need to use the corresponding integer values. You can use the ord() function to convert a character to its corresponding integer value:
Example
Section titled “Example”Python Data Type Conversion
Section titled “Python Data Type Conversion”Sometimes we need to convert between built-in data types. Simply use the data type name as a function. This will be covered in detail in the next chapter Python3 Data Type Conversion.
The following built-in functions can perform conversions between data types. These functions return a new object representing the converted value:
| Function | Description |
| int(x [,base]) | Converts x to an integer |
| float(x) | Converts x to a floating-point number |
| complex(real [,imag]) | Creates a complex number |
| str(x) | Converts object x to a string |
| repr(x) | Converts object x to an expression string |
| eval(str) | Evaluates a valid Python expression in a string and returns an object |
| tuple(s) | Converts sequence s to a tuple |
| list(s) | Converts sequence s to a list |
| set(s) | Converts to a mutable set |
| dict(d) | Creates a dictionary. d must be a sequence of (key, value) tuples |
| frozenset(s) | Converts to an immutable set |
| chr(x) | Converts an integer to its corresponding character |
| ord(x) | Converts a character to its integer value (Unicode code point) |
| hex(x) | Converts an integer to a hexadecimal string |
| oct(x) | Converts an integer to an octal string |