I. Basic Concepts of the Four Data Types
Python provides a variety of built-in data structures for organizing and managing data. Among them, strings, lists, tuples and sets are used very frequently.
They each solve different data organization problems:
| Data Type | Type Name | Core Characteristics | Typical Use |
|---|---|---|---|
| String | str |
Immutable sequence of characters | Text, descriptions, encoded data |
| List | list |
Ordered, mutable, allows duplicates | Dynamic data collections |
| Tuple | tuple |
Ordered, immutable, allows duplicates | Data with a fixed structure |
| Set | set |
Unordered, mutable, unique elements | Deduplication, intersection, union |
1. Strings (str)
A string is used to store text data and is an immutable sequence composed of Unicode characters.
name = "Python"
message = "Hello World"
print(name[0]) # P
print(name[1:4]) # yth
print(len(name)) # 6
Main characteristics of strings:
- Ordered: characters can be accessed by index.
- Immutable: the characters in it cannot be modified directly after creation.
- Allows duplicates: can contain repeated characters.
- Supports slicing: a portion of the string can be extracted.
- Supports string concatenation, search, replacement and formatting.
The immutability of strings means that modification operations usually create a new string.
text = "Python"
# Creates a new string rather than modifying the original string
new_text = text.replace("P", "J")
print(text) # Python
print(new_text) # Jython
2. Lists (list)
A list is used to store multiple elements and is the most common mutable sequence type in Python.
numbers = [10, 20, 30, 40]
print(numbers[0]) # 10
numbers[1] = 200
numbers.append(50)
print(numbers)
# [10, 200, 30, 40, 50]
Main characteristics of lists:
- Ordered: elements are arranged by position.
- Mutable: elements can be modified, added and removed.
- Allows duplicates: can store identical elements.
- Supports indexing and slicing.
- Can store data of different types.
- Can nest other lists or containers.
Lists are suitable for managing data whose quantity and content may change.
3. Tuples (tuple)
A tuple is an immutable sequence, usually used to store data with a fixed structure.
user = ("Alice", 25, "Beijing")
print(user[0]) # Alice
print(user[1]) # 25
Main characteristics of tuples:
- Ordered: elements can be accessed by index.
- Immutable: elements cannot be replaced, added or removed directly.
- Allows duplicates: can contain identical values.
- Supports indexing and slicing.
- Can store data of different types.
- When all elements are hashable, a tuple itself can also serve as a dictionary key or a set element.
Single-element tuples require special attention:
a = (10)
b = (10,)
print(type(a)) # <class 'int'>
print(type(b)) # <class 'tuple'>
The key to creating a tuple is the comma, not the parentheses.
4. Sets (set)
A set is used to store unique elements and is suitable for deduplication and set operations.
numbers = {10, 20, 30, 20, 10}
print(numbers)
# {10, 20, 30}
Main characteristics of sets:
- Does not guarantee the insertion order of elements.
- Does not support indexing or slicing.
- Elements are unique; duplicate elements are merged.
- The set itself is mutable; elements can be added and removed.
- Elements in a set must be hashable.
- Supports union, intersection, difference and symmetric difference.
An empty set must be created using set():
empty_set = set()
empty_dict = {}
print(type(empty_set)) # <class 'set'>
print(type(empty_dict)) # <class 'dict'>
Note that elements in a set are not necessarily immutable objects, but they must be hashable objects. Therefore, lists and dictionaries cannot be used directly as set elements.
II. Core Differences Between the Four Data Types
To understand the four data types, we first need to compare them across four dimensions: ordering, mutability, duplicates and access method.
1. Differences in Ordering
| Data type | Ordered | Supports indexing |
|---|---|---|
str |
Ordered | Yes |
list |
Ordered | Yes |
tuple |
Ordered | Yes |
set |
Order not guaranteed | No |
Strings, lists, and tuples are all sequence types, and their elements have definite positions.
text = "Python"
items = [10, 20, 30]
points = (1, 2, 3)
print(text[0]) # P
print(items[0]) # 10
print(points[0]) # 1
Sets do not support index access:
numbers = {10, 20, 30}
# Not supported
# print(numbers[0]) # TypeError
If you need to process a set in a certain order, you can use sorted():
numbers = {30, 10, 20}
result = sorted(numbers)
print(result)
# [10, 20, 30]
Note: sorted() returns a list, not a set.
2. Differences in mutability
Mutability determines whether the contents of an object can be modified directly on the original object after it is created.
| Data type | Mutability | Typical operations |
|---|---|---|
str |
Immutable | replace(), upper() |
list |
Mutable | append(), remove() |
tuple |
Immutable | Read, iterate |
set |
Mutable | add(), discard() |
Strings are immutable:
text = "hello"
# Modifying characters directly is not allowed
# text[0] = "H"
text = "Hello"
print(text)
Lists are mutable:
numbers = [1, 2, 3]
numbers[0] = 100
numbers.append(4)
print(numbers)
# [100, 2, 3, 4]
Tuples are immutable:
user = ("Alice", 25)
# Modifying tuple elements is not allowed
# user[1] = 30
Sets are mutable:
colors = {"red", "blue"}
colors.add("green")
colors.discard("red")
print(colors)
Being immutable does not mean a variable cannot be reassigned; it means the internal structure cannot be changed through operations that modify the object's own contents.
text = "hello"
text = "world"
This code does not modify the original string; instead, it rebinds the variable text to another string object.
3. Whether duplicate elements are allowed
| Data type | Allows duplicates |
|---|---|
str |
Yes |
list |
Yes |
tuple |
Yes |
set |
No |
Strings allow duplicate characters:
text = "hello"
print(text)
# hello
Lists allow duplicate elements:
numbers = [1, 2, 2, 3, 3, 3]
print(numbers)
Tuples allow duplicate elements:
values = (10, 10, 20, 20)
print(values)
Sets automatically eliminate duplicate elements:
numbers = {1, 2, 2, 3, 3, 3}
print(numbers)
# {1, 2, 3}
Sets determine duplicates mainly by hashing and equality checks. If two elements are equal and have the same hash value, they are treated as the same element in a set.
4. Element Type Restrictions
The four data types have different requirements for their elements.
| Data Type | Element Type Restriction |
|---|---|
str |
The elements are Unicode characters in the string |
list |
Can store any Python object |
tuple |
Can store any Python object |
set |
Elements must be hashable |
Lists can store a mix of different types:
data = [
100,
"Python",
True,
3.14,
[1, 2, 3]
]
Tuples can also store different types:
user = (
1001,
"Alice",
25,
True
)
Sets can only store hashable objects:
valid_set = {
10,
"Python",
(1, 2, 3)
}
# The following operation is not allowed
# invalid_set = {[1, 2], [3, 4]}
Common unhashable objects include:
listdictset
Common hashable objects include:
intfloatstrboolbytesfrozenset
Whether a tuple is hashable depends on whether all of its elements are hashable.
a = (1, 2, 3)
b = (1, [2, 3])
print(hash(a)) # can be computed
# hash(b) will raise TypeError
III. Indexing, Slicing, and Access Methods
Strings, lists, and tuples are all sequence types, so they support indexing and slicing.
Sets are not sequences and do not support these two access methods.
1. Indexing
Indexes start at 0, and negative indexes are also supported.
text = "Python"
items = [10, 20, 30, 40]
points = (1, 2, 3, 4)
print(text[0]) # P
print(items[1]) # 20
print(points[-1]) # 4
Negative indexes count from the end of the sequence:
| Index | Meaning |
|---|---|
0 |
The first element |
1 |
The second element |
-1 |
The last element |
-2 |
The second-to-last element |
2. Slicing
Slicing syntax:
sequence[start:stop:step]
Where:
start: The starting position, inclusive.stop: The ending position, exclusive.step: The step size; the default is1.
String slicing:
text = "Python"
print(text[0:3]) # Pyt
print(text[2:]) # thon
print(text[::-1]) # nohtyP
List slicing:
numbers = [10, 20, 30, 40, 50]
print(numbers[1:4])
# [20, 30, 40]
Tuple slicing:
points = (1, 2, 3, 4, 5)
print(points[1:4])
# (2, 3, 4)
Slicing does not modify the original string, list, or tuple. Slicing a list returns a new list, and slicing a tuple returns a new tuple.
Note that list slicing is a shallow copy. If the list contains other mutable objects, the inner objects may still be shared by multiple lists.
3. Set Access Methods
Set elements cannot be accessed by index:
numbers = {10, 20, 30}
# numbers[0] # TypeError
When you need to iterate over a collection, you can use for:
for number in numbers:
print(number)
If you need to obtain a stable sorted result:
for number in sorted(numbers):
print(number)
4. Common Operations for the Four Data Types
Although all four types can store data, the operation methods they provide differ significantly.
1. Common String Operations
| Operation | Purpose | Example |
|---|---|---|
upper() |
Convert to uppercase | "python".upper() |
lower() |
Convert to lowercase | "PYTHON".lower() |
strip() |
Remove whitespace from both ends | " hi ".strip() |
replace() |
Replace content | "abc".replace("a", "x") |
split() |
Split a string | "a,b".split(",") |
join() |
Join strings | ",".join(["a", "b"]) |
find() |
Find a substring | "python".find("th") |
startswith() |
Check whether it starts with | "python".startswith("py") |
Example:
text = " Python Programming "
clean_text = text.strip()
upper_text = clean_text.upper()
words = clean_text.split()
print(clean_text)
print(upper_text)
print(words)
Common string processing methods do not modify the original string in place; instead, they return the processed result.
2. Common List Operations
| Operation | Purpose | Example |
|---|---|---|
append() |
Add one element | items.append(10) |
extend() |
Add multiple elements | items.extend([20, 30]) |
insert() |
Insert at a specified position | items.insert(0, 10) |
remove() |
Remove the first matching value | items.remove(10) |
pop() |
Remove and return an element | items.pop() |
clear() |
Clear the list | items.clear() |
index() |
Find the position of an element | items.index(20) |
count() |
Count occurrences of an element | items.count(10) |
sort() |
Sort in place | items.sort() |
reverse() |
Reverse in place | items.reverse() |
copy() |
Shallow copy | items.copy() |
Example:
numbers = [30, 10, 20]
numbers.append(40)
numbers.extend([50, 60])
numbers.sort()
print(numbers)
# [10, 20, 30, 40, 50, 60]
Note: sort() modifies the original list and returns None.
If you need to produce a new sorted list, use sorted().
3. Common Tuple Operations
You cannot directly add, delete, or replace elements in a tuple, but you can query and iterate over it.
| Operation | Purpose | Example |
|---|---|---|
count() |
Count occurrences of an element | items.count(10) |
index() |
Find the position of an element | items.index(20) |
len() |
Get the number of elements | len(items) |
in |
Check whether an element exists | 10 in items |
| Slicing | Get some of the elements | items[1:3] |
| Unpacking | Assign elements to variables | a, b = items |
Example:
```python user = ("Alice", 25, "Beijing") name = user[0] age = user[1] print(name) print(age) # tuple unpacking name, age, city = user print(name, age, city) ```If you really need to modify the data in a tuple, you can first convert it to a list, make the change, and then convert it back to a tuple:
```python user = ("Alice", 25, "Beijing") user_list = list(user) user_list[1] = 26 user = tuple(user_list) print(user) # ('Alice', 26, 'Beijing') ```This approach creates a new container; it does not modify the original tuple directly.
4. Common Set Operations
| Operation | Purpose | Example |
|---|---|---|
add() |
Add an element | items.add(10) |
update() |
Add multiple elements | items.update([20, 30]) |
remove() |
Remove a specified element | items.remove(10) |
discard() |
Remove an element without raising an error if it doesn't exist | items.discard(10) |
pop() |
Remove and return an element | items.pop() |
clear() |
Empty the set | items.clear() |
copy() |
Shallow copy | items.copy() |
union() |
Union | a.union(b) |
intersection() |
Intersection | a.intersection(b) |
difference() |
Difference | a.difference(b) |
symmetric_difference() |
Symmetric difference | a.symmetric_difference(b) |
Example:
```python numbers = {1, 2, 3} numbers.add(4) numbers.update([5, 6]) numbers.discard(2) print(numbers) ```There is an important difference between a set's remove() and discard():
If you are not sure whether an element exists, discard() is usually more convenient.
V. Set Operations: The Unique Power of Sets
The biggest advantage of sets is that they can perform mathematical set operations directly.
Assume there are two sets:
python_students = {"Alice", "Bob", "Charlie"}
java_students = {"Bob", "David", "Charlie"}
1. Union
The union is the set of all unique elements from both sets.
result = python_students | java_students
print(result)
# {'Alice', 'Bob', 'Charlie', 'David'}
You can also use:
result = python_students.union(java_students)
2. Intersection
The intersection is the set of elements that exist in both sets at the same time.
result = python_students & java_students
print(result)
# {'Bob', 'Charlie'}
You can also use:
result = python_students.intersection(java_students)
3. Difference
The difference is the set of elements that exist in the first set but not in the second set.
result = python_students - java_students
print(result)
# {'Alice'}
The difference is directional:
a = {1, 2, 3}
b = {2, 3, 4}
print(a - b) # {1}
print(b - a) # {4}
4. Symmetric difference
The symmetric difference is the set of elements that exist in only one of the two sets, but not in both at the same time.
result = python_students ^ java_students
print(result)
# {'Alice', 'David'}
You can also use:
result = python_students.symmetric_difference(java_students)
5. Testing set relationships
Sets also support testing subset, superset and disjoint relationships.
a = {1, 2}
b = {1, 2, 3, 4}
c = {5, 6}
print(a.issubset(b)) # True
print(b.issuperset(a)) # True
print(a.isdisjoint(c)) # True
You can also use comparison operators:
print(a <= b) # True, a is a subset of b
print(b >= a) # True, b is a superset of a
Note: < and > on sets mean the strict subset and strict superset relationships, not an ordering by the number of elements.
VI. Converting between the four data types
Python provides built-in constructors such as str(), list(), tuple() and set(), which can convert between different containers.
1. Conversion relationships
| Conversion | Example | Result |
|---|---|---|
| String to list | list("abc") |
['a', 'b', 'c'] |
| String to tuple | tuple("abc") |
('a', 'b', 'c') |
| String to set | set("hello") |
A set of characters with duplicates removed |
| List to string | str([1, 2]) |
"[1, 2]" |
| List to tuple | tuple([1, 2]) |
(1, 2) |
| List to set | set([1, 2, 2]) |
{1, 2} |
| Tuple to list | list((1, 2)) |
[1, 2] |
| Tuple to set | set((1, 2, 2)) |
{1, 2} |
| Set to list | list({1, 2}) |
A list; order is not guaranteed |
| Set to tuple | tuple({1, 2}) |
A tuple; order is not guaranteed |
2. Converting Strings to Lists, Tuples, and Sets
text = "hello"
a = list(text)
b = tuple(text)
c = set(text)
print(a)
# ['h', 'e', 'l', 'l', 'o']
print(b)
# ('h', 'e', 'l', 'l', 'o')
print(c)
# {'h', 'e', 'l', 'o'}
When converting a string to a set, duplicate characters are removed.
3. Converting Lists to Tuples and Sets
numbers = [1, 2, 2, 3, 3, 4]
a = tuple(numbers)
b = set(numbers)
print(a)
# (1, 2, 2, 3, 3, 4)
print(b)
# {1, 2, 3, 4}
Converting a list to a tuple preserves element order and duplicate values.
Converting a list to a set removes duplicates, but no longer preserves the ordering guarantees of the original list.
4. Converting Sets to Lists
numbers = {30, 10, 20}
result = list(numbers)
print(result)
When converting a set to a list, you should not rely on the order of the resulting elements.
If you need sorted order:
result = sorted(numbers)
print(result)
# [10, 20, 30]
5. Difference Between String Concatenation and Container Conversion
It is important to note that str() does not concatenate the elements in a container one by one into a string.
numbers = [1, 2, 3]
print(str(numbers))
# [1, 2, 3]
If you need to concatenate a list of strings, use join():
words = ["Python", "is", "powerful"]
result = " ".join(words)
print(result)
# Python is powerful
If the list contains non-string elements, you need to convert the elements to strings first:
numbers = [1, 2, 3]
result = ",".join(str(number) for number in numbers)
print(result)
# 1,2,3
VII. Underlying Implementation and Performance Differences
The four data types differ not only in how they are used; in common Python implementations, their internal storage methods also differ significantly.
Note that the underlying implementations below mainly use CPython as an example. The Python language specification defines observable behavior and does not require all interpreters to use the same data structures.
1. String str: Immutable Text Sequence
CPython uses dedicated string objects to represent text.
Key characteristics:
- Strings are immutable.
- They support Unicode text.
- Strings can cache their hash values.
- String concatenation may create new objects.
- String slicing usually creates a new string object.
Example:
text = "Hello"
new_text = text + " World"
print(text)
print(new_text)
Frequently using + to concatenate a large number of strings may produce many intermediate objects.
A more suitable approach is usually to collect the strings first and then use join():
parts = []
for i in range(5):
parts.append(f"item-{i}")
result = ",".join(parts)
print(result)
2. list: Dynamic Array
In CPython, lists typically use a dynamic array to store object references.