Skip to content

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:

#!/usr/bin/python3

counter = 100          # Integer variable
miles   = 1000.0       # Float variable
name    = "runoob"     # String

print(counter)
print(miles)
print(name)

Run Example »

Running the above program produces the following output:

100
1000.0
runoob

Python allows you to assign values to multiple variables simultaneously. For example:

a = b = c = 1

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:

a, b, c = 1, 2, "runoob"

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:

# Variable definition
x = 10           # Integer
y = 3.14         # Float
name = "Alice"   # String
is_active = True # Boolean

# Multi-variable assignment
a, b, c = 1, 2, "three"

# Check data types
print(type(x))         # <class 'int'>
print(type(y))         # <class 'float'>
print(type(name))      # <class 'str'>
print(type(is_active)) # <class 'bool'>

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.


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.

>>> 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'>

Additionally, you can use isinstance() to check:

>>> a = 111
>>> isinstance(a, int)
True

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.
>>> 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. True and False can be added to numbers. True==1 and False==0 will return 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
<stdin>:1: SyntaxWarning: "is" with 'int' literal. Did you mean "=="?
False
>>> 0 is False
<stdin>:1: SyntaxWarning: "is" with 'int' literal. Did you mean "=="?
False

Why does SyntaxWarning appear?

Python detects that you are using is to compare a literal integer (like 1) with True, which is usually a code error — because is compares 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:

var1 = 1
var2 = 10

You can use the del statement to delete object references:

del var1[, var2[, var3[...., varN]]]

For example:

del var
del var_a, var_b
>>> 5 + 4   # Addition
9
>>> 4.3 - 2 # Subtraction
2.3
>>> 3 * 7   # Multiplication
21
>>> 2 / 4   # Division, returns a float
0.5
>>> 2 // 4  # Floor division, returns an integer
0
>>> 17 % 3  # Modulo
2
>>> 2 ** 5  # Exponentiation
32

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.
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 the 0o prefix (e.g., 0o17), hexadecimal uses the 0x prefix (e.g., 0x69), and binary uses the 0b prefix.

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.


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:

variable[start_index:end_index]

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:

#!/usr/bin/python3

my_str = 'Runoob'       # Define a string variable (avoid using str as a variable name; it overrides the built-in type)

print(my_str)           # Print the entire string: Runoob
print(my_str[0:-1])     # Print characters from index 0 to the second-to-last (excluding the last): Runoo
print(my_str[0])        # Print the first character: R
print(my_str[2:5])      # Print characters at indices 2, 3, 4 (excluding index 5): noo
print(my_str[2:])       # Print from index 2 to the end: noob
print(my_str * 2)       # Repeat twice: RunoobRunoob
print(my_str + "TEST")  # String concatenation: RunoobTEST

Running the above program produces the following output:

Runoob
Runoo
R
noo
noob
RunoobRunoob
RunoobTEST

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:

>>> print('Ru\noob')
Ru
oob
>>> print(r'Ru\noob')
Ru\noob

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.

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

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 r prefix 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.

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: True and False.
  • bool is a subclass of int, so boolean values can be used as integers, where True is equivalent to 1 and False is equivalent to 0.
  • Boolean types can be compared with other data types, such as numbers, strings, etc. When comparing, Python treats True as 1 and False as 0.
  • Boolean types can be used with logical operators, including and, or, and not, to combine multiple boolean expressions.
  • Boolean types can also be converted to other data types, such as integers, floats, and strings. When converting, True is converted to 1 and False is converted to 0.
  • You can use the bool() function to convert values of other types to boolean values. The following values are False when converted to boolean: None, False, zero (0, 0.0, 0j), empty sequences (like '', (), []), and empty mappings (like {}). All other values are True when converted to boolean.
# Boolean type values and types
a = True
b = False
print(type(a))  # <class 'bool'>
print(type(b))  # <class 'bool'>

# Integer representation of booleans
print(int(True))   # 1
print(int(False))  # 0

# Conversion using the bool() function
print(bool(0))          # False
print(bool(42))         # True
print(bool(''))         # False
print(bool('Python'))   # True
print(bool([]))         # False
print(bool([1, 2, 3]))  # True

# Boolean logical operations
print(True and False)  # False
print(True or False)   # True
print(not True)        # False

# Boolean comparison operations
print(5 > 3)   # True
print(2 == 2)  # True
print(7 < 4)   # False

# Boolean values in control flow
if True:
    print("This will always print")

if not False:
    print("This will also always print")

x = 10
if x:
    print("x is non-zero, and is True in a boolean context")

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:

variable[start_index:end_index]

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:

#!/usr/bin/python3

my_list = ['abcd', 786, 2.23, 'runoob', 70.2]  # Avoid using list as a variable name; it overrides the built-in type
tinylist = [123, 'runoob']

print(my_list)             # Print the entire list: ['abcd', 786, 2.23, 'runoob', 70.2]
print(my_list[0])          # Print the first element (index 0): abcd
print(my_list[1:3])        # Print elements at indices 1 and 2 (excluding index 3): [786, 2.23]
print(my_list[2:])         # Print from index 2 to the end: [2.23, 'runoob', 70.2]
print(tinylist * 2)        # Repeat tinylist twice: [123, 'runoob', 123, 'runoob']
print(my_list + tinylist)  # Concatenate two lists

The above example outputs:

['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:

>>> 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, effectively deleting them
>>> a
[9, 2, 6]

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:

def reverseWords(input):

    # Split the string by spaces, separating each word into a list
    inputWords = input.split(" ")

    # inputWords[-1::-1] three parameters explained:
    # First parameter -1 means starting from the last element
    # Second parameter is empty, meaning move to the beginning of the list
    # Third parameter -1 means step backward (move one position left each time)
    inputWords = inputWords[-1::-1]

    # Rejoin the words with spaces
    output = ' '.join(inputWords)

    return output

if __name__ == "__main__":
    input = 'I like runoob'
    rw = reverseWords(input)
    print(rw)

The output is:

runoob like I

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:

#!/usr/bin/python3

my_tuple = ('abcd', 786, 2.23, 'runoob', 70.2)  # Avoid using tuple as a variable name
tinytuple = (123, 'runoob')

print(my_tuple)               # Output the complete tuple
print(my_tuple[0])            # Output the first element: abcd
print(my_tuple[1:3])          # Output elements at indices 1 and 2: (786, 2.23)
print(my_tuple[2:])           # Output all elements from index 2 onward
print(tinytuple * 2)          # Output tinytuple twice
print(my_tuple + tinytuple)   # Concatenate two tuples

The above example outputs:

('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 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.

>>> tup = (1, 2, 3, 4, 5, 6)
>>> print(tup[0])
1
>>> print(tup[1:5])
(2, 3, 4, 5)
>>> tup[0] = 11  # Modifying tuple elements is illegal
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: 'tuple' object does not support item assignment

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:

tup1 = ()    # Empty tuple
tup2 = (20,) # Single element tuple; a comma must be added after the element

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:

not_a_tuple = (42)  # This is the integer 42, not a tuple

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:

parame = {value01, value02, ...}
or
set(value)
#!/usr/bin/python3

sites = {'Google', 'Taobao', 'Runoob', 'Facebook', 'Zhihu', 'Baidu'}

print(sites)   # Output the set (unordered; duplicate elements are automatically removed)

# Membership test
if 'Runoob' in sites:
    print('Runoob is in the set')
else:
    print('Runoob is not in the set')

# Sets can perform set operations
a = set('abracadabra')
b = set('alacazam')

print(a)           # Unique characters in a

print(a - b)       # Difference of a and b (elements in a but not in b)
print(a | b)       # Union of a and b (elements in a or b)
print(a & b)       # Intersection of a and b (elements in both a and b)
print(a ^ b)       # Symmetric difference of a and b (elements in a or b, but not both)

The above example outputs:

{'Zhihu', 'Baidu', 'Taobao', 'Runoob', 'Google', 'Facebook'}
Runoob is in the set
{'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 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.

#!/usr/bin/python3

my_dict = {}
my_dict['one'] = "1 - Rookie Tutorial"
my_dict[2]     = "2 - Rookie Tools"

tinydict = {'name': 'runoob', 'code': 1, 'site': 'www.runoob.com'}

print(my_dict['one'])       # Output the value for key 'one'
print(my_dict[2])           # Output the value for key 2
print(tinydict)             # Output the complete dictionary
print(tinydict.keys())      # Output all keys
print(tinydict.values())    # Output all values

The above example outputs:

1 - Rookie Tutorial
2 - Rookie Tools
{'name': 'runoob', 'code': 1, 'site': 'www.runoob.com'}
dict_keys(['name', 'code', 'site'])
dict_values(['runoob', 1, 'www.runoob.com'])

The dict() constructor can build a dictionary directly from a sequence of key-value pairs:

>>> 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, Google=2, Taobao=3)
{'Runoob': 1, 'Google': 2, 'Taobao': 3}

{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.

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:

x = b"hello"           # Create a bytes object using the b prefix
print(x)               # b'hello'
print(type(x))         # <class 'bytes'>
print(x[0])            # 104 (ASCII value of 'h'; bytes elements are integers)

You can also use the bytes() function to convert other types of objects to bytes type. The second parameter specifies the encoding method:

x = bytes("hello", encoding="utf-8")

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:

x = b"hello"
y = x[1:3]          # Slicing operation, yields b'el'
z = x + b"world"    # Concatenation operation, yields b'helloworld'
print(y)            # b'el'
print(z)            # b'helloworld'

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:

x = b"hello"
if x[0] == ord("h"):    # ord("h") returns 104
    print("The first element is 'h'")

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