Fundamentals 10 min read

Python Built‑in Data Types: Numbers, Strings, Booleans, Sequences, Mappings, Sets, Conversions and Others

This tutorial introduces Python's built‑in data types—including numbers, strings, booleans, lists, tuples, dictionaries, sets, and conversion functions—explaining their characteristics, common operations, and providing ready‑to‑run code examples for each type.

Test Development Learning Exchange
Test Development Learning Exchange
Test Development Learning Exchange
Python Built‑in Data Types: Numbers, Strings, Booleans, Sequences, Mappings, Sets, Conversions and Others

Introduction

Python provides a rich set of built‑in data types that serve as the foundation for storing and manipulating values in programs. Understanding these types and their operations is essential for writing clear and efficient Python code.

1. Basic Data Types

Numbers include integers, floats and complex numbers. Integers have unlimited precision, floats follow the IEEE‑754 standard, and complex numbers have real and imaginary parts.

# 整数
a = 42
b = -7
c = 0
# 浮点数
x = 3.14
y = -0.001
z = 2.0
# 复数
c1 = 2 + 3j
c2 = 4 - 5J
# 算术运算
result = 10 + 5  # 15
result = 10 - 5  # 5
result = 10 * 5  # 50
result = 10 / 5  # 2.0
result = 10 % 3  # 1
result = 2 ** 3  # 8
# 比较运算
is_equal = 10 == 5  # False
is_greater = 10 > 5  # True

Strings are immutable sequences of characters, created with single or double quotes. Common operations include concatenation, repetition, indexing, slicing, and a variety of string methods.

# 字符串
s1 = 'Hello, World!'
s2 = "Python"
# 拼接
greeting = "Hello" + ", " + "World!"  # "Hello, World!"
# 重复
repeated = "Hi " * 3  # "Hi Hi Hi "
# 索引和切片
first_char = s1[0]  # 'H'
substring = s1[7:12]  # "World"
# 查找子字符串
index = s1.find("World")  # 7
# 字符串方法
upper_case = s1.upper()  # "HELLO, WORLD!"
lower_case = s1.lower()  # "hello, world!"
stripped = "   Hello, World!   ".strip()  # "Hello, World!"
split_words = s1.split(", ")  # ['Hello', 'World!']

Booleans have two values, True and False, and are used in logical expressions.

# 布尔值
is_valid = True
is_empty = False
# 逻辑运算
result = True and False  # False
result = True or False   # True
result = not True        # False

2. Sequence Types

List is an ordered, mutable collection that can hold heterogeneous elements. Common operations include appending, extending, inserting, removing, popping, indexing, slicing, and list comprehensions.

# 列表
my_list = [1, 2, 3, "four", 5.0]
# 添加元素
my_list.append(6)               # [1, 2, 3, "four", 5.0, 6]
my_list.extend([7, 8])          # [1, 2, 3, "four", 5.0, 6, 7, 8]
my_list.insert(0, "start")     # ["start", 1, 2, 3, "four", 5.0, 6, 7, 8]
# 删除元素
my_list.remove("four")         # [1, 2, 3, 5.0, 6, 7, 8]
popped_element = my_list.pop(2) # 3
del my_list[0]                  # [2, 3, 5.0, 6, 7, 8]
# 修改元素
my_list[0] = 0                  # [0, 3, 5.0, 6, 7, 8]
# 索引和切片
first_element = my_list[0]      # 0
sub_list = my_list[1:4]         # [3, 5.0, 6]
# 列表推导式
squares = [x ** 2 for x in range(1, 6)]  # [1, 4, 9, 16, 25]

Tuple is an ordered, immutable collection.

# 元组
my_tuple = (1, 2, 3, "four", 5.0)
# 索引和切片
first_element = my_tuple[0]   # 1
sub_tuple = my_tuple[1:4]      # (2, 3, 'four')
# 元组解包
a, b, c, d, e = my_tuple   # a=1, b=2, c=3, d='four', e=5.0

String is also a sequence type but immutable (see section 1).

3. Mapping Type

Dictionary stores unordered, mutable key‑value pairs. Keys must be immutable, values can be any type.

# 字典
my_dict = {
    "name": "Alice",
    "age": 30,
    "city": "New York"
}
# 添加键值对
my_dict["email"] = "[email protected]"
# 删除键值对
del my_dict["age"]
email = my_dict.pop("email")
# 访问键值对
name = my_dict["name"]
# 获取所有键/值/项
keys = my_dict.keys()
values = my_dict.values()
items = my_dict.items()
# 检查键是否存在
has_name = "name" in my_dict
has_email = "email" in my_dict

4. Set Type

Sets are unordered collections of unique elements that support mathematical operations such as union, intersection, difference, and symmetric difference.

# 集合
my_set = {1, 2, 3, 4, 5}
# 添加元素
my_set.add(6)               # {1, 2, 3, 4, 5, 6}
# 删除元素
my_set.remove(3)            # {1, 2, 4, 5, 6}
my_set.discard(7)           # no error
popped_element = my_set.pop()# removes an arbitrary element
# 集合运算
set1 = {1, 2, 3}
set2 = {3, 4, 5}
union = set1 | set2               # {1, 2, 3, 4, 5}
intersection = set1 & set2        # {3}
difference = set1 - set2          # {1, 2}
symmetric_difference = set1 ^ set2 # {1, 2, 4, 5}
# 检查元素是否存在
has_1 = 1 in set1               # True
has_4 = 4 in set1               # False

5. Type Conversion

# 转换为整数
num = int(3.14)          # 3
# 转换为浮点数
num = float(3)           # 3.0
# 转换为字符串
num_str = str(3.14)      # "3.14"
# 转换为列表
list_from_string = list("hello")  # ['h', 'e', 'l', 'l', 'o']
# 转换为元组
tuple_from_list = tuple([1, 2, 3]) # (1, 2, 3)
# 转换为集合
set_from_list = set([1, 2, 3, 3])   # {1, 2, 3}

6. Other Built‑in Types

None represents the absence of a value. value = None bytes and bytearray are sequences of bytes; bytes is immutable while bytearray is mutable.

# bytes
data = b'Hello, World!'
# bytearray
mutable_data = bytearray(b'Hello, World!')
mutable_data[0] = 72  # modifies first byte

Conclusion

Python offers a comprehensive set of built‑in data types, each with specific use‑cases and operations; mastering them is crucial for developing efficient, readable Python programs.

Original Source

Signed-in readers can open the original source through BestHub's protected redirect.

Sign in to view source
Republication Notice

This article has been distilled and summarized from source material, then republished for learning and reference. If you believe it infringes your rights, please contactadmin@besthub.devand we will review it promptly.

PythonData TypesTutorialprogramming fundamentals
Test Development Learning Exchange
Written by

Test Development Learning Exchange

Test Development Learning Exchange

0 followers
Reader feedback

How this landed with the community

Sign in to like

Rate this article

Was this worth your time?

Sign in to rate
Discussion

0 Comments

Thoughtful readers leave field notes, pushback, and hard-won operational detail here.