SoFunction
Updated on 2024-11-10

Introduction to commonly used data structures in python

a wooden or bamboo pen for sheep or cattle

# Use a List as a stack
stack = [3, 4, 5]

# Into the stack
(6)
# Out of the stack
val = ()
# Stacked elements
val = stack[-1]

formation

Queue is FIFO, but List is not efficient enough for First Out. Usually use double-ended queue Deque to realize the queue.

Deque is characterized by O(1) time complexity for both additions and deletions at both ends

from collections import deque
queue = deque(["Eric", "John", "Michael"])

# Into the queue
("Terry")
# Out of the queue
()

tuple

Very similar to List, but Tuple is immutable data structure

# created, the right side of the equal sign can be expanded with parentheses
empty = ()
xyz = 12345, 54321, 'hello!'
one = 12345,
## Unpacking
x, y, z = xyz
x, = one

It is possible to have mutable elements like a List inside a Tuple.

a = [1,2,3]
b = [4,5,6]
# created, the right side of the equal sign can be expanded with parentheses
t = (a, b) 
# ([1, 2, 3], [4, 5, 6])
(4)
(7)
print(t)
# ([1, 2, 3, 4], [4, 5, 6, 7])

If Tuple is sufficiently satisfied, then Tuple consists of two advantages.

  • Tuples are naturally thread-safe due to their immutability
  • Tuples are better than lists in terms of space occupied.
import sys
t = tuple(range(2 ** 24))
l = [i for i in range(2 ** 24)]

# Compare memory usage
print((t), (l)) 

Tuple creation method

import timeit

# Convert Tuple from Range This is the fastest and recommended method.
('''t = tuple(range(10000))''', number = 10000)

# Create Tuple from List
('''t = tuple([i for i in range(10000)])''', number = 10000)

# Create Tuple from Range
('''t = tuple(i for i in range(10000))''', number = 10000)

# Unpacking generator to create Tuple
('''t = *(i for i in range(10000)),''', number = 10000)

Range

A type of sequential data structure (List, Tuple, Range), often used with For loops.

# 0 - 9
val = range(10)
val = range(0, 10)
val = range(0, 10, 1)

set (mathematics)

empty = set()
a = {1, 2, 3, 3, 3, 2}
b = {1, 3, 5, 7, 9}

# Supersets and subsets
a <= b
(b)
(a)

# Intersection
intersection = a & b
# And the concatenation
union = a | b
# Differences
subtraction = a - b
# Symmetry difference
symmetric_difference = a ^ b

dictionaries

A dictionary consists of (Key: Value) pairs, where the Key is required to be of immutable type (String, Number, etc.).

So a Tuple can be used as a Key, but a List cannot.

# {'sape': 4139, 'guido': 4127, 'jack': 4098}
d = dict([('sape', 4139), ('guido', 4127), ('jack', 4098)])

# {2: 4, 4: 16, 6: 36}
d = {x: x**2 for x in (2, 4, 6)}

# {'sape': 4139, 'guido': 4127, 'jack': 4098}
d = dict(sape=4139, guido=4127, jack=4098)

However, if the Tuple contains a variable type, then it cannot be used as a Key either, and the following error occurs.

TypeError: unhashable type: 'list'

generative

Generative (List Comprehensions) to provide a concise way to create a list of

# [0, 1, 4, 9, 16, 25, 36, 49, 64, 81]
# Create lists
squares = []
for x in range(10):
 (x**2)

# Generative
squares = [x**2 for x in range(10)]

conditional statement

# [(1, 3), (1, 4), (2, 3), (2, 1), (2, 4), (3, 1), (3, 4)]
[(x, y) for x in [1,2,3] for y in [3,1,4] if x != y]

Using Functions

# ['3.1', '3.14', '3.142', '3.1416', '3.14159']
from math import pi
[str(round(pi, i)) for i in range(1, 6)]

generative nesting

matrix = [
  [1, 2, 3, 4],
  [5, 6, 7, 8],
  [9, 10, 11, 12],
]

# rows and columns
matrix = [[row[i] for i in range(len(row))] for row in matrix]

# Columns and rows
transposed = [[row[i] for row in matrix] for i in range(4)]
transposed = list(zip(*matrix))

generator

Generators are similar to generative syntax, except that generators are in lazy load mode and do not generate the entire list immediately

import sys
# elements are ready, consume more memory
l = [i for i in range(2 ** 24)] 
print((l)) 
# 146916504 // 8 = 2 ** 24 

# Create generator objects, takes no extra space, but requires internal arithmetic when data is required
l = (i for i in range(2 ** 24)) 
print((l)) 
# 128 

In addition to the generator syntax above, there is another one via the yield keyword

def fib(n):
  a, b = 0, 1
  for _ in range(n):
    a, b = b, a + b
    yield a

if __name__ == '__main__':
  for val in fib(20):
    print(val)

circulate

list cycle

l = ['tic', 'tac', 'toe']

for index in range(len(l))
 print(index, l[index])

for val in l:
 print(val)

for index, val in enumerate(l):
 print(index, val)

dictionary cycle

d = {'gallahad': 'the pure', 'robin': 'the brave'}

for key in d:
 print(key, d[key])

for key, val in ():
 print(key, val)

reversed

# [0, 2, 4, 6, 8]
for num in range(0, 10, 2):
 print(num)

# [8, 6, 4, 2, 0]
for num in reversed(range(0, 10, 2)):
 print(num)

zip

Returns an iterator over Tuple, with the i-th element coming from each of the i-th elements of the arguments, and with a length equal to the shortest argument.

The above is the introduction of commonly used data structures in python in detail, more information about python data structures please pay attention to my other related articles!