laitimes

Five steps to mastering Python data structures

Five steps to mastering Python data structures

Introduction to Python data structures

Four basic Python data structures:

  • List - Ordered, variable, repeatable elements. Useful for storing data series.
  • Tuple - Ordered, immutable, repeatable elements. Think of them as immutable lists.
  • Dictionary - Unordered, mutable, mapped by key-value pairs. Useful for storing data in key-value format.
  • Collection - Unordered, mutable, contains unique elements. Useful for membership testing and de-duplication.

In addition to basic data structures, Python provides more advanced structures such as heaps, queues, and linked lists, which can further enhance your coding capabilities. These high-level structures are built on an infrastructure that enables more complex data processing and is often used for special scenarios. But not limited here; You can also use all existing structures as a basis to implement your own.

Step 1: Use lists in Python

What is a list in Python?

A list in Python is an ordered, mutable data type that can store a variety of objects and allows repeating elements. The list is defined by using square brackets [ ], with elements separated by commas.

For example:

fibs = [0, 1, 1, 2, 3, 5, 8, 13, 21]           

Lists are useful for organizing and storing data sequences.

Create a list

Lists can contain different data types such as strings, integers, Booleans, and so on. For example:

mixed_list = [42, "Hello World!", False, 3.14159]           

List of actions

You can access, add, change, and delete elements in the list. For example:

# 访问第二个元素(索引从’0’开始)
print(mixed_list[1])

# 添加元素
mixed_list.append("This is new")

# 更改元素
mixed_list[0] = 5

# 删除第一元素
mixed_list.pop(0)           

List method

Some handy built-in listing methods include:

  • sort() - Sorts the list in place
  • append() - Adds an element to the end of the list
  • insert() - Inserts the element at the index
  • pop() - Deletes the element at the index
  • remove() - Removes the value of the first occurrence
  • reverse() - Invert the list in place

example

# 生成列表
cart = ["apples", "oranges", "grapes"]

# Sort the list 
cart.sort()

# Add new item 
cart.append("blueberries") 

# Remove first item
cart.pop(0)

print(cart)           

Output:

['grapes', 'oranges', 'blueberries']           

Step 2: Understand tuples in Python

What is a tuple?

A tuple is another sequence data type in Python, similar to a list. However, unlike lists, tuples are immutable, meaning that their elements cannot be changed once created. They are defined by enclosing the element in parentheses ( ).

# Defining a tuple
my_tuple = (1, 2, 3, 4)           

When to use tuples

Tuples are typically used for collections of items that should not be modified. Tuples are faster than lists, which makes them ideal for read-only operations. Some common use cases include:

  • Stores constant or configuration data
  • A function with multiple components returns values
  • Dictionary keys because they are hashable

Access the tuple element

Elements in a tuple are accessed in a similar way to access list elements. Indexes and tiles work the same way.

# 访问元组
first_element = my_tuple[0]
sliced_tuple = my_tuple[1:3]           

Tuple operations

Since tuples are immutable, many list operations such as append() or remove() do not apply. However, there are still a few things you can do:

  • Concatenation: Use the + operator to combine tuples.
concatenated_tuple = my_tuple + (5, 6)           
  • Repeat: Use the operator to repeat the tuple*.
repeated_tuple = my_tuple * 2           
  • Membership: Check if there are elements with the keyword in the tuple.
exists = 1 in my_tuple           

Tuple method

Given the immutable nature of tuples, there are fewer built-in methods for tuples than lists. Some useful methods include:

  • count(): Counts the number of occurrences of a particular element.
count_of_ones = my_tuple.count(1)           
  • index(): Finds the index at which a value first appears.
index_of_first_one = my_tuple.index(1)           

Tuple packaging and unpacking

Tuple packing and unpacking is a handy feature in Python:

  • Packing: Assign multiple values to a single tuple.
packed_tuple = 1, 2, 3           
  • Unpack: Assign tuple elements to multiple variables.
a, b, c = packed_tuple           

Immutable but not strict

While tuples themselves are immutable, they can contain mutable elements, such as lists.

# 包含可变列表的元组
complex_tuple = (1, 2, [3, 4])           

Note that while you cannot change the tuple itself, you can modify the mutable elements in it.

Step 3: Master the Python dictionary

What is a dictionary in Python?

A dictionary in Python is an unordered, mutable data type that stores unique key-to-value mappings. The dictionary is written in curly braces { } and consists of comma-separated key-value pairs.

For example:

student = {"name": "Michael", "age": 22, "city": "Chicago"}           

Dictionaries are useful for storing data in a structured way and accessing values through keys.

Create a dictionary

The dictionary key must be an immutable object, such as a string, number, or tuple. Dictionary values can be any object.

student = {"name": "Susan", "age": 23}

prices = {"milk": 4.99, "bread": 2.89}           

Manipulate dictionaries

Elements can be accessed, added, changed, and deleted by keystrokes.

# 根据键访问元素
print(student["name"])

# 增加一个新的键值对
student["major"] = "computer science"  

# 改变一个的键值
student["age"] = 25

# 删除一个键值对
del student["city"]           

Dictionary method

Some useful built-in methods include:

  • keys() - Returns a list of keys
  • values() - Returns a list of values
  • items() - Returns (key, value) tuples
  • get() - Returns the value of the key, avoiding KeyError
  • pop() - Deletes the key and returns the value
  • update() - Add multiple key values

example

scores = {"Francis": 95, "John": 88, "Daniel": 82}

# 增加新成绩
scores["Zoey"] = 97

# 删除John的成绩
scores.pop("John")  

# 访问Daniel的成绩
print(scores.get("Daniel"))

# 打印所有同学的名字
print(scores.keys())           

Step 4: Collections in Python

What are collections in Python?

A collection in Python is an unordered, mutable collection of unique, immutable objects. Collections are { } written in curly braces, but unlike dictionaries, collections do not have key-value pairs.

For example:

numbers = {1, 2, 3, 4}           

Collections are useful for membership testing, de-duplication, and mathematical operations.

Create a collection

You can create a collection from a list by passing it to the constructor set():

my_list = [1, 2, 3, 3, 4]
my_set = set(my_list) # {1, 2, 3, 4}           

Collections can contain mixed data types, such as strings, Booleans, and so on.

Operation set

You can add and remove elements from a collection.

numbers.add(5) 

numbers.remove(1)           

Set operations

Some useful set operations include:

  • union() - Returns the union of two collections
  • intersection() - Returns the intersection of collections
  • difference() - Returns the difference between collections
  • symmetric_difference()—Returns the symmetric difference

Collection example

A = {1, 2, 3, 4}
B = {2, 3, 5, 6}

# Union - 合运算
print(A | B) 

# 交运算
print(A & B)

# 差运算
print(A - B)

# 对称差运算
print(A ^ B)           

Step 5: Comparison of lists, tuples, dictionaries, and collections

data structure Whether it is orderly Variable Repeating elements example
list yes yes yes Storage sequence
Tuples yes No yes Stores immutable sequences
dictionary No yes

Key: None

Value: Yes

Stores key-value pairs
gather No yes No Eliminate duplicates, membership testing

When to use each data structure

  • Use lists to get ordered, sequence-based data. Useful for stacks/queues.
  • Use tuples to represent ordered, immutable sequences. Useful when you need a fixed set of elements that should not be changed.
  • Use dictionaries to store key-value data. Useful for storing related properties.
  • Use collections to store unique elements and mathematical operations.