timerring

Python Composite Data Type

December 21, 2024 · 8 min read · Page View:
Tutorial
Python
If you have any questions, feel free to comment below.

This article will review the composite data type in Python, such as list, tuple, dictionary, and set.

CH3 Composite Data Type #

List #

List Definition #

  • Sequence type: Internal elements have positional relationships and can be accessed by position number
  • List is a sequence type that can use multiple types of elements, supports element addition, deletion, query, and modification operations
ls = ["Python", 1989, True, {"version": 3.7}]
  • Another way to generate: list(iterable), iterable includes: string, tuple, set, range, etc.
list("Welcome to subscribe this column")
# ['W', 'e', 'l', 'c', 'o', 'm', 'e', ' ', 't', 'o', ' ', 's', 'u', 'b', 's', 'c', 'r', 'i', 'b', 'e', ' ', 't', 'h', 'i', 's', ' ', 'c', 'o', 'l', 'u', 'm', 'n']
list(("I", "am", "a", "student"))
# ['I', 'am', 'a', 'student']
list({"Jim", "Green"})
# ['Green', 'Jim']

range(start number, end number, number interval)

  • If the start number is omitted, it defaults to 0
  • Must include the end number, closed on the left and open on the right
  • The number interval is omitted, it defaults to 1
for i in range(1, 11, 2):
    print(i)
# 1
# 3
# 5
# 7
# 9
list(range(1, 11, 2))
# [1, 3, 5, 7, 9]

List Properties #

  • List length —— len(list)
  • List index —— Same as string
cars = ["BYD", "BMW", "AUDI", "TOYOTA"]
print(cars[0])
# BYD

List Slicing #

variable name[start position:end position:slice interval]

cars = ["BYD", "BMW", "AUDI", "TOYOTA"]
print(cars[:3])     # The first three elements, start position omitted, defaults to 0; slice interval omitted, defaults to 1
# ['BYD', 'BMW', 'AUDI']
print(cars[1:4:2])  # The second to fourth elements, the difference between the front and back index is 2
# ['BMW', 'TOYOTA']
print(cars[:])      # Get the entire list, end position omitted, defaults to the last
# ['BYD', 'BMW', 'AUDI', 'TOYOTA']
print(cars[-4:-2])  # Get the first two elements
# ['BYD', 'BMW']
  • Reverse slicing
cars = ["BYD", "BMW", "AUDI", "TOYOTA"]
print(cars[:-4:-1])      # Start position omitted, defaults to -1
# ['TOYOTA', 'AUDI', 'BMW']
print(cars[::-1])        # Get the reverse list
# ['TOYOTA', 'AUDI', 'BMW', 'BYD']

List Operators #

  • Use + to concatenate lists
  • Use * to multiply lists
[0]*10 # [0, 0, 0, 0, 0, 0, 0, 0, 0, 0]

List Methods #

Add Element #

  • Add element to the end —— list.append(element)
  • Insert element at any position —— list.insert(position number, element)
  • Append another list to the end —— list.extend(another list)

append will add the entire list as a single element to the end of the list.

languages.append(["Ruby", "PHP"])
# ['Python', 'C', 'C++', 'R', 'Java', ['Ruby', 'PHP']]

extend will add each element in the second list to the first list.

languages = ['Python', 'C', 'C++', 'R', 'Java']
languages.extend(["Ruby", "PHP"])
# ['Python', 'C', 'C++', 'R', 'Java', 'Ruby', 'PHP']

Delete Element #

  • Delete element at list i position —— list.pop(i)
languages = ['Python', 'C', 'C++', 'R', 'Java']
languages.pop(1)
# ['Python', 'C++', 'R', 'Java']
  • Do not write position information, default to delete the last element —— list.pop()
  • Delete the first occurrence of the element to be deleted in the list —— list.remove(element)

Find Element #

  • The position of the first occurrence of the element to be searched in the list —— list.index(element)

Modify Element #

  • Modify element by “index first, then assign” —— list[position]=new value

List Copy #

  • languages_2 = languages Incorrect way: This only creates an alias for the list

  • Correct way —— Shallow copy

  • Method 1: list.copy()

  • Method 2: list[:] is equivalent to slicing the entire list

List Sorting #

  • Use list.sort() to sort the list in place, no return value, default to increasing. Decreasing order list.sort(reverse = True)
  • Use sorted(list) to temporarily sort the list, the original list remains unchanged, and the sorted list is returned. The same decreasing order sorted(list, reverse = True)

List Reversal #

  • Use list.reverse() to reverse the list in place, no return value

List Traversal #

  • Use for loop

Tuple #

Tuple Expression #

  • Treat the tuple as an “immutable list”
  • Does not support element addition, element deletion, element modification operations, and other operations are completely consistent with list operations

Common Uses of Tuple #

Packing and Unpacking

  • Example 1: The return value is packaged as a tuple
def f1(x):
    return x**2, x**3 # Packing return

print(f1(3))
# (9, 27)
print(type(f1(3)))
# <class 'tuple'>
a, b = f1(3) # Unpacking assignment 
print(a) # 9
print(b) # 27
  • Example 2: Use zip function to pack
numbers = [201901, 201902, 201903]
name = ["Apple", "Google", "Tesla"]
list(zip(numbers, name))
# [(201901, 'Apple'), (201902, 'Google'), (201903, 'Tesla')]

# Unpack each tuple immediately
for number,name in zip(numbers,name):
    print(number, name)
# 201901 Apple
# 201902 Google
# 201903 Tesla

Dictionary #

Dictionary Expression #

  • Regular dictionary is unordered and can only be accessed by key

Dictionary Key Requirements

Dictionary keys cannot be repeated. If they are repeated, the previous keys are overwritten.

Dictionary keys must be immutable types,if the key is mutable, the corresponding stored value cannot be found.

  • Immutable types: numbers, strings, tuples.
  • Mutable types: lists, dictionaries, sets. Once determined, they can be freely added, deleted, and modified. Therefore, these three types cannot be used as dictionary keys.

Dictionary Properties #

  • Dictionary length len() —— Number of key-value pairs
  • Dictionary index, get the corresponding value through dictionary[key]

Dictionary Operations #

Add key-value pair

  • variable name[new key] = new value

Delete key-value pair

  • del variable name[key to be deleted]
  • variable name.pop(key to be deleted)
  • variable name.popitem() Randomly delete a key-value pair and return it as a tuple

Modify value

  • Modify the corresponding value through “index first, then assign”

d.get( )

  • d.get(key, default) Get the value corresponding to the key from the dictionary d, if there is no such key, return default

  • Example: Count the frequency of characters in “牛奶奶找刘奶奶买牛奶”

s = "牛奶奶找刘奶奶买牛奶"
d = {}
print(d)
for i in s:
    d[i] = d.get(i, 0)+1 # If the character appears for the first time, return default 0, then add 1 to count. If there is already a key i, return the value corresponding to the key i.
    print(d)
# {}
# {'牛': 1}
# {'牛': 1, '奶': 1}
# {'牛': 1, '奶': 2}
# {'牛': 1, '奶': 2, '找': 1}
# {'牛': 1, '奶': 2, '找': 1, '刘': 1}
# {'牛': 1, '奶': 3, '找': 1, '刘': 1}
# {'牛': 1, '奶': 4, '找': 1, '刘': 1}
# {'牛': 1, '奶': 4, '找': 1, '刘': 1, '买': 1}
# {'牛': 2, '奶': 4, '找': 1, '刘': 1, '买': 1}
# {'牛': 2, '奶': 5, '找': 1, '刘': 1, '买': 1}

d.keys( ) d.values( )

Get all keys and values separately.

students = {201901: 'Apple', 201902: 'Google', 201903: 'Tesla'}
print(list(students.keys()))
print(list(students.values()))
# [201901, 201902, 201903]
# ['Apple', 'Google', 'Tesla']

d.items( )

print(list(students.items()))
# [(201901, 'Apple'), (201902, 'Google'), (201903, 'Tesla')]
for k, v in students.items(): # Unpack
    print(k, v)
# 201901 Apple
# 201902 Google
# 201903 Tesla

Set #

Set Expression #

  • A collection of unordered elements that are mutually exclusive, which can be used for deduplication
  • Elements must be immutable types: numbers, strings, or tuples, which can be considered as the keys of dictionaries
  • Can be considered as a dictionary without values or values as None

Set Operations #

  • S & T Returns a new set, including elements that are in both sets S and T
  • S | T Returns a new set, including all elements in sets S and T
  • S ^ T Returns a new set, including non-common elements in sets S and T
  • S - T Returns a new set, including elements in set S but not in set T

Set Methods #

  • Add element S.add(x)
  • Remove element S.remove(x)
  • Set length len(S)
  • Set traversal —— Use for loop
for star in stars:
    print(star)

Related readings


<< prev | Python Basic... Continue strolling Python Control... | next >>

If you find this blog useful and want to support my blog, need my skill for something, or have a coffee chat with me, feel free to: