Python Lists, Tuples, and Dictionaries: Definitions, Operations, and Traversal
This article introduces Python’s core data structures—lists, tuples, and dictionaries—explaining their definitions, common operations such as adding, modifying, searching, deleting, sorting, nesting, and how to iterate over them, accompanied by clear code examples.
1. List
Unlike arrays in many other languages, a Python list can contain elements of different types, which makes it extremely powerful.
<code>my_list = [1, "xin", (1,), {"yi"}, ["nice"], {"hello": "world"}]</code>A list may hold int, str, tuple, list, dict, and other objects simultaneously.
2. Basic List Operations
Add elements (append, extend, insert):
<code># Empty list
my_list = list()
# append adds an element to the end
my_list.append("罗罗诺亚")
my_list.append("索隆")
# extend adds each element from another iterable
b = ["三刀流", "奥义"]
my_list.extend(b) # ["罗罗诺亚", "索隆", "三刀流", "奥义"]
# using + operator as a shortcut
my_list = my_list + b
# insert inserts an element before the given index
my_list.insert(0, "帅的一笔")
</code>Modify elements (by index):
<code>my_list = [1, 2, 3, 4]
my_list[0] = "修改" # ["修改", 2, 3, 4]
</code>Search elements (in, not in, index, count):
<code>my_list = [1, 2, 3]
"1" in my_list # False
"1" not in my_list # True
my_list.index(1, 0, 2) # 0 (search in slice [0,2))
my_list.count(1) # 1
</code>Delete elements (del, pop, remove):
<code># del removes by index
my_list = [1, 2, 3]
del my_list[0] # [2, 3]
# pop removes and returns an element (default last)
my_list.pop(1) # removes element at index 1, result [2]
# remove deletes the first occurrence of a value
my_list.remove(2) # []
</code>Sort (sort, reverse):
<code>my_list = [1, 4, 2, 3]
my_list.sort() # [1, 2, 3, 4]
my_list.sort(reverse=True) # [4, 3, 2, 1]
my_list.reverse() # reverses order in‑place
</code>3. List Nesting
<code># Nested lists are equivalent to multidimensional arrays in other languages
my_list = [
["北京大学", "清华大学"],
["南开大学", "天津大学", "天津师范大学"],
["山东大学", "中国海洋大学"]
]
</code>2. Tuple
Python tuples are similar to lists but immutable; they use parentheses instead of brackets.
Definition
<code># Single‑element tuple requires a trailing comma
my_tuple = ("a", )
# Multiple‑element tuple
my_tuple = ("a", "b")
</code>Immutability
Tuple elements cannot be modified after creation.
Common Methods
count and index work the same way as for lists and strings.
3. Dictionary
A dictionary stores key‑value pairs; it is analogous to JSON objects (keys must be strings).
Definition
<code>my_dict = {
"name": "索隆",
"sex": "男"
}
</code>Common Operations
Access values by key:
<code>name = my_dict["name"] # raises KeyError if missing
name = my_dict.get("age") # returns None if missing
name = my_dict.get("age", 10) # returns default value 10 if missing
</code>Modify / add elements :
<code># Modify existing key
my_dict["name"] = "路飞"
# Add new key
my_dict["age"] = 18
</code>Delete elements :
<code># Delete a specific key
del my_dict["age"]
# Delete the entire dictionary
del my_dict
# Clear all items
my_dict.clear()
</code>Utility functions :
<code>len(my_dict) # number of key‑value pairs
my_dict.keys() # view of all keys
my_dict.values() # view of all values
my_dict.items() # view of (key, value) tuples
</code>4. Traversal
Lists, Tuples, and Strings
<code>my_str = "hello world"
my_list = ["hello", "world"]
my_tuple = ("hello", "world")
# Simple iteration
for i in my_list:
print(i)
# With index using enumerate
for index, value in enumerate(my_list):
print(index, value)
</code>Dictionary Traversal
Iterate over keys:
<code>for key in my_dict.keys():
print(key)
</code>Iterate over values:
<code>for value in my_dict.values():
print(value)
</code>Iterate over items (key‑value pairs):
<code>for item in my_dict.items():
print(item) # prints a tuple like ("name", "路飞")
</code>Iterate with unpacking:
<code>for key, value in my_dict.items():
print(key)
print(value)
</code>Python Programming Learning Circle
A global community of Chinese Python developers offering technical articles, columns, original video tutorials, and problem sets. Topics include web full‑stack development, web scraping, data analysis, natural language processing, image processing, machine learning, automated testing, DevOps automation, and big data.
How this landed with the community
Was this worth your time?
0 Comments
Thoughtful readers leave field notes, pushback, and hard-won operational detail here.