YouTip LogoYouTip

Python3 Data Type

Python3 Basic Data Types

Python3.x Python3 Basic Data Types

In Python, variables do not need to be declared. Each variable must be assigned a value before use; the variable is only created after assignment. In Python, a variable is just a variableβ€”it has no type. The "type" we refer to 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+)

#!/usr/bin/python3

counter = 100             # Integer variable
miles   = 1000.0          # Floating point variable
name    = ""        # String

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

Run Example Β»

Executing the above program outputs the following result:
100
1000.0

Multiple Assignment

Python allows you to assign values to multiple variables simultaneously. For example:
a = b = c = 1
The example above creates one integer object with the value 1, and three variables are assigned the same value. You can also assign different values to multiple variables at once. For example:
a, b, c = 1, 2, ""
In the example above, the integer objects 1 and 2 are assigned to variables a and b respectively, and the string object "" is assigned to variable c. You can check the type of a variable using the type() function:

Example

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

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

Standard Data Types

Python3 has 6 standard data types, plus the bool (boolean) type (bool is a subclass of int, sometimes listed separately):
  • Number
  • String
  • bool (Boolean)
  • List
  • Tuple
  • Set
  • Dictionary
By mutability, 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 array type.

Number (Numeric)

Python3 supports int, float, bool, and complex (complex numbers). In Python 3, there is only one integer type int, represented as long integers. There is no Long type as in Python 2. The built-in type() function can be used to query the type of 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'>
You can also use isinstance() for checking:

Example

>>> 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. This is usually a code error because is compares object identity (whether they are the same object), not whether values are equal. Python suggests using == to compare values, unless you specifically need to check if 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 use the del statement to delete object references:
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, returns a float
0.5
>>> 2 // 4      # Floor division, returns an integer
0
>>> 17 % 3      # Modulus
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 pointed to objects of different types through assignment.
  • Numeric division includes two operators: / returns a float, // returns an integer (floor division).
  • In mixed calculations, Python will automatically convert 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 do not allow leading zeros (e.g., 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 and can be represented as a + bj or complex(a, b). Both the real part a and the imaginary part b are floats.

String

In Python, strings are enclosed in single quotes ' or double quotes ". The backslash is used to escape special characters. The syntax for string slicing is:
variable[head_index:tail_index]
Index values start at 0, and -1 represents the position from the end.

Image 1

The plus sign + is the string concatenation operator, and the asterisk * indicates repetition. The number combined with it indicates the number of repetitions. Examples are as follows:

Example

#!/usr/bin/python3

my_str = ''          # Define a string variable (avoid using 'str' as a variable name, it would overwrite the built-in type)

print(my_str)               # Print the entire string: 
print(my_str[0:-1])         # Print characters from index 0 to the second-to-last (excluding the last): Runoo
print(my_str)            # Print the first character: R
print(my_str[2:5])          # Print characters at index 2, 3, 4 (excluding index 5): noo
print(my_str[2:])           # Print from index 2 to the end: noob
print(my_str * 2)           # Print the string twice: TutorialTutorial
print(my_str + "TEST")      # String concatenation: TutorialTEST
Executing the above program outputs the following result:

Runoo
R
noo
noob
TutorialTutorial
TutorialTEST
Python uses the backslash to escape special characters. If you don't want the backslash to be interpreted as an escape character, you can add an r before the string to indicate a raw string:

Example

>>> print('Run oob')

Ru

oob

>>> print(r'Run oob')

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 a string of length 1.

Example

>>> word = 'Python'
>>> print(word, word)
P n
>>> print(word, word)
n P
Unlike C strings, Python strings cannot be changed. Assigning a value to an index position, such as word = 'm', will result in an error. Note:
  • Backslashes can be used for escaping. Using the r prefix prevents the backslash from being interpreted (raw string).
  • Strings can be concatenated using the + operator and repeated using the * operator.
  • In Python, strings have two indexing methods: starting from 0 going left to right, and starting from -1 going right to left.
  • Strings in Python are immutable; they cannot be changed.

bool (Boolean Type)

The boolean type is either True or False. In Python, both True and False are keywords representing boolean values. The boolean type can be used to control the flow of a program, such as checking whether a condition is met or executing a block of code when a certain 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 used as integers, where True is equivalent to 1 and False is equivalent to 0.
  • The boolean type can be compared with other data types, such as numbers and strings. In comparisons, Python treats True as 1 and False as 0.
  • The boolean type can be used with logical operators, including and, or, and not, to combine multiple boolean expressions.
  • The boolean type can also be converted to other data types, such as integers, floats, and strings. In conversion, True becomes 1 and False becomes 0.
  • You can use the bool() function to convert values of other types to boolean values. The following values convert to False: None, False, zero (0, 0.0, 0j), empty sequences (like '', (), []), and empty mappings (like {}). All other values convert to True.

Example

# Boolean values and types
a = True
b = False
print(type(a))  # <class 'bool'>
print(type(b))  # <class 'bool'>

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

# Using the bool() function for conversion
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

# Using 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 a non-zero value 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 considered True. Only 0, empty strings, empty lists, empty tuples, etc. are considered False. Therefore, when performing boolean type conversions, it is important to be aware of the truthiness of the data type.

List

Lists are the most frequently used data type in Python. Lists can implement most collection-like data structures. The types of elements in a list can be different; they support numbers, strings, and can even include other lists (i.e., nested lists). Lists are written between square brackets [], with elements separated by commas. Similar to 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[head_index:tail_index]
Index values start at 0, and -1 represents the position from the end.

Image 2

The plus sign + is the list concatenation operator, and the asterisk * is the repetition operator. Examples are as follows:

Example

#!/usr/bin/python3

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

print(my_list)          # Print the entire list: ['abcd', 786, 2.23, '', 70.2]
print(my_list)       # Print the first element (index 0): abcd
print(my_list[1:3])     # Print elements at index 1 and 2 (excluding index 3): [786, 2.23]
print(my_list[2:])      # Print all elements from index 2 to the end: [2.23, '', 70.2]
print(tinylist * 2)     # Print tinylist twice: [123, '', 123, '']
print(my_list + tinylist)  # Concatenate the two lists
The output of the above example is:
['abcd', 786, 2.23, '', 70.2]
abcd
[786, 2.23]
[2.23, '', 70.2]
[123, '', 123, '']
['abcd', 786, 2.23, '', 70.2, 123, '']
Unlike Python strings, the elements in a list can be changed:

Example

>>> a = [1, 2, 3, 4, 5, 6]
>>> a = 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 these elements
>>> a
[9, 2, 6]
Lists have many built-in methods, such as append(), pop(), etc., which will be discussed later. Note:
  • Lists are written between square brackets, with elements separated by commas.
  • Like strings, lists can be indexed and sliced.
  • Lists can be concatenated using the + operator.
  • The elements in a list can be changed (mutable type).
Python list slicing can accept a third parameter, which specifies the step size for slicing. The following example slices a list from index 1 to index 4 with a step size of 2 (taking every other element):

Image 3

If the third parameter is negative, it indicates reading in reverse order. The following example is used to reverse the order of words in a string:

Example

def reverseWords(input):
    # Split the string by spaces to separate the words into a list
    inputWords = input.split(" ")

    # The inputWords[-1::-1] slice with three parameters:
    # The first parameter -1 indicates starting from the last element
    # The second parameter is empty, indicating moving to the beginning of the list
    # The third parameter -1 indicates reverse stepping (moving one position to the left each time)
    inputWords = inputWords[-1::-1]

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

    return output

if __name__ == "__main__":
    input = 'I like '
    rw = reverseWords(input)
    print(rw)
The output is:
 like I

Tuple

A tuple is similar to a list, but the difference is that the elements of a tuple cannot be modified. Tuples are written in parentheses (), with elements separated by commas. The types of elements in a tuple can also be different:

Example

#!/usr/bin/python3

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

print(my_tuple)             # Print the entire tuple
print(my_tuple)          # Print the first element: abcd
print(my_tuple[1:3])        # Print elements at index 1 and 2: (786, 2.23)
print(my_tuple[2:])         # Print all elements from index 2 to the end
print(tinytuple * 2)        # Print tinytuple twice
print(my_tuple + tinytuple) # Concatenate the two tuples
The output of the above example is:
('abcd', 786, 2.23, '', 70.2)
abcd
(786, 2.23)
(2.23, '', 70.2)
(123, '', 123, '')
('abcd', 786, 2.23, '', 70.2, 123, '')
Tuples are similar to strings in that they can be indexed starting from 0, and -1 represents the position from the end. They can also be sliced. In fact, a string can be considered a special kind of tuple.

Example

>>> tup = (1, 2, 3, 4, 5, 6)
>>> print(tup)
1
>>> print(tup[1:5])
(2, 3, 4, 5)
>>> tup = 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 are immutable, it can contain mutable objects, like lists. Constructing tuples containing 0 or 1 element requires special syntax:
tup1 = ()      # Empty tuple
tup2 = (20,)   # A single element; a comma must be added after the element
If you want to create a tuple with a single element, you need to add a comma after the element to distinguish it from a regular value. Because without the comma, Python interprets the parentheses as mathematical grouping:
not_a_tuple = (42)  # This is the integer 42, not a tuple
string, list, and tuple all belong to the sequence type. Note:
  • Like strings, the elements of a tuple cannot be modified (immutable type).
  • Tuples can also be indexed and sliced using the same methods as lists.
  • Pay attention to the special syntax for constructing tuples containing 0 or 1 element.
  • Tuples can also be concatenated using the + operator.

Set

A set in Python is an unordered, mutable data type used to store unique elements. The elements in a set are not repeated and can perform common set operations such as intersection, union, and difference. In Python, sets are represented by curly braces {}, with elements separated by commas ,. You can also create a set using the set() function.

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)

Example

#!/usr/bin/python3

sites = {'Google', 'Taobao', '', 'Facebook', 'Zhihu', 'Baidu'}
print(sites)  # Print the set (unordered; duplicate elements are automatically removed)

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

# Set operations
a = set('abracadabra')
b = set('alacazam')

print(a)          # Unique characters in a
print(a - b)      # Difference of a and b (in a but not in b)
print(a | b)      # Union of a and b (in a or b)
print(a & b)      # Intersection of a and b (in both a and b)
print(a ^ b)      # Symmetric difference of a and b (in a or b but not both)
The output of the above example is:
{'Zhihu', 'Baidu', 'Taobao', '', 'Google', 'Facebook'}
 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

The 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 use immutable types, and within the same dictionary, keys must be unique.

Note: Starting from Python 3.7, dictionaries maintain the insertion order of elements and are no longer unordered. If you need the characteristics of an ordered dictionary, you can directly use a regular dict.

Example

#!/usr/bin/python3

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

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

print(my_dict['one'])       # Print the value with key 'one'
print(my_dict)           # Print the value with key 2
print(tinydict)             # Print the entire dictionary
print(tinydict.keys())      # Print all keys
print(tinydict.values())    # Print all values
The output of the above example is:
1 - 
2 -  Tools
{'name': '', 'code': 1, 'site': 'www..com'}
dict_keys(['name', 'code', 'site'])
dict_values(['', 1, 'www..com'])
The constructor dict() can directly build a dictionary from a sequence of key-value pairs:

Example

>>> dict([('', 1), ('Google', 2), ('Taobao', 3)])
{'': 1, 'Google': 2, 'Taobao': 3}

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

>>> dict(=1, Google=2, Taobao=3)
{'': 1, 'Google': 2, 'Taobao': 3}
{x: x**2 for x in (2, 4, 6)} uses a dictionary comprehension. For more on comprehensions, refer to: Python Comprehensions. Additionally, the dictionary type has some built-in functions, such as clear(), keys(), values(), etc. Note:
  • A dictionary is a mapping type; its elements are key-value pairs.
  • The keys of a dictionary must be of an immutable type and cannot be repeated.
  • To create an empty dictionary, use {}.
  • Starting from Python 3.7, dictionaries maintain insertion order.

bytes Type

In Python3, the bytes type represents an immutable binary sequence. Unlike the string type, the elements of a 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 using the b prefix:

Example

x = b"hello"  # Create a bytes object using the b prefix
print(x)         # b'hello'
print(type(x))   # <class 'bytes'>
print(x)      # 104 (ASCII value of 'h'; bytes elements are integers)
You can also use the bytes() function to convert objects of other types to bytes. The second parameter specifies the encoding:
x = bytes("hello", encoding="utf-8")
Similar to the string type, the bytes type also supports operations like slicing, concatenation, finding, and replacing. Since the bytes type is immutable, modification operations require creating a new bytes object:

Example

x = b"hello"
← Os RemovedirsOs Remove β†’