SoFunction
Updated on 2024-11-07

An article to help you figure out data containers in Python

I. Data container: list (list)

Each piece of data within the list, called an element

  • Marked with []
  • Separate each element of the list with a, comma.

Define the syntax:

[Element 1, Element 2, Element 3, ......]

Example:

list = ['iii', 666, 'Hello']

1.1 List Removing Elements

Each element in the list is indexed by its position subscript, which is incremented or decremented from 0 in the front-to-back direction.

Syntax: list [subscript], you can take out the

1.2 Common operations (methods) for lists

1.2.1 Query functions for lists (methods)

Function: Find the subscript of the specified element in the list, if you can't find it, report an error ValueError

Syntax: list.index(element)

1.2.2 List modification functions (methods)

Modifies the value of an element at a specific location (index):

Grammar:List[subscript] = value

You can use the above syntax to directly: reassign (modify) the value of a specified subscript (both forward and reverse subscripts are allowed)

Insert the element:

Grammar:list.insert(subscript, element)The following is an example of how to insert the specified element at the specified subscript position.

Additional elements.

Grammar:list.append(element)The following is an example of how to append a specified element to the end of a list.

Append element way 2:

Grammar:List.extend(other data container)If you want to add the contents of other data containers to the end of the list, you can do so by removing them from the list.

Delete the element:

  • Grammar 1:del list [subscript]
  • Grammar 2:List.pop(subscript)

Removes the first match of an element in a list.

Grammar:list.remove(element)

Empty list content.

Grammar:List.clear()

Counting the number of elements in a list

Grammar:List.count(elements)

1.2.3 Query functions for lists (methods)

Count how many elements are in the list

Grammar:len(list)

You can get an int number indicating the number of elements in the list

list = [21, 25, 21, 23, 22, 20]

(31)
([29, 33, 30])
listone = ()
idx = (31)
print(idx)
Usage corresponds English -ity, -ism, -ization
list.append(element) Add an element to the list
List.extend(container) Remove the contents of the data container in order and append them to the end of the list.
list.insert(subscript, element) Inserts the specified element at the specified subscript.
del list [subscript] Deletes the specified subscript element of the list
List.pop(subscript) Deletes the specified subscript element of the list
list.remove(element) Remove the first match of this element, from front to back.
List.clear() Empty the list
List.count(elements) Counts the number of times this element appears in the list
List.index(element) Finds the subscript of the specified element in the list
ValueError not found.
len(list) Counts how many elements are in the container

1.3 Characteristics of the list

  • Can hold multiple elements (upper limit of 2**63-1, 9223372036854775807)
  • Can accommodate different types of elements (mixed loads)
  • Data is stored in an ordered fashion (with subscripted serial numbers)
  • Allow duplicate data to exist
  • Can be modified (add or remove elements, etc.)

1.4 List Iteration

1.4.1 Iterating through lists - while loops

def while_list():
    list = [11, 12, 13]
    index = 0
    while index < len(list):
        el = list[index]
        print(f'elemental:{el}')

        index += 1

while_list()

1.4.2 Iterating through lists - for loops

def for_list():
    list = [1, 2, 3, 4, 5]
    for v in list:
        print(f'elemental:{v}')

for_list()

Exercise example: taking out even numbers from a list

list = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
index = 0
new_list = []
while index < len(list):
    if list[index] % 2 == 0:
        new_list.append(list[index])

    index += 1

for val in list:
    if val % 2 == 0:
        new_list.append(val)

print(new_list)

II. Data container: tuple (tuple)

Tuple Definition: Define tuples using parentheses and commas to separate individual data, which can be of different data types.

Once a tuple is defined, it cannot be modified

Tuples have very few methods of manipulation due to their unmodifiable nature.

Tuples can also be traversed, just like lists.

It can be traversed using while loops and for loops

methodologies corresponds English -ity, -ism, -ization
index() Find a certain data, if the data exists return the corresponding subscript, otherwise report an error
count() Counts the number of times a piece of data appears in the current tuple
len(tuple) Counting the number of elements in a tuple
t1 = (1, 11)
print(f'{t1}, type:{type(t1)}')
num = (11)

Characteristics of tuples.

  • Can hold multiple data
  • Can hold different types of data (mixed loads)
  • Data is stored in an ordered fashion (subscript index)
  • Allow duplicate data to exist
  • Cannot be modified (adding or removing elements, etc.)
  • Support for for loops

III. Data container: str (string)

3.1 String subscripts (indexes)

Like other containers such as lists and tuples, strings can be accessed by subscripts.

  • From front to back, subscripts start at 0
  • Back to front, with subscripts starting at -1

Like a tuple, a string is a: container of data that cannot be modified.

So:

  • Modify the character of the specified subscript (e.g., string[0] = "a")
  • Remove characters with specific subscripts (e.g., del string[0], string.remove(), string.pop(), etc.)
  • Append characters, etc. (e.g., string.append())
  • Neither can be done. If you have to do it, you can only get a new string, the old one cannot be modified.

3.2 Summary of common string operations

manipulate clarification
String [subscript] Takes out a specific character at a specific position according to the subscript index
String.index(string) Finds the subscript of the first match for a given character
String.replace(string1, string2) Replace all of string 1 with string 2.
does not modify the original string, but instead gets a new
String.split(string) Separate the strings according to the given strings <br/> does not modify the original strings, but gets a new list
String.strip()<br/> String.strip(string) Remove leading and trailing spaces and line breaks or specified strings
String.count(string) Counting the number of occurrences of a string within a string
len(string) Counting the number of characters in a string

3.3 String Iteration

Like lists and tuples, strings support while loops and for loops for traversal.

str = 'Tiny Tinker Bell'
index = 0
while index < len(str):
    print(str[index])
    index += 1


for v in str:
    print(v)

3.4 Characteristics of strings

As a data container, strings have the following characteristics:

  • Only strings can be stored
  • Arbitrary length (depending on memory size)
  • Supports subscript indexing
  • Allow duplicate strings to exist
  • Cannot be modified (adding or removing elements, etc.)
  • Support for for loops

IV. Slicing of data containers (sequences)

Sequences support slicing, i.e. lists, tuples, strings, all support slicing operations
Slicing: from a sequence, take out a subsequence

Syntax: sequence [start subscript:end subscript:step]

Indicates that from the sequence, starting from the specified position, the elements are taken out sequentially, ending at the specified position, and a new sequence is obtained:

The start subscript indicates where to start, and can be left blank; leaving it blank is treated as starting from the beginning.

The end subscript (not included) indicates where to end, and can be left blank, leaving it blank is regarded as intercepting to the end.

The step size indicates the interval at which the elements are taken sequentially

  • Step 1 means that the elements are taken one by one
  • Step 2 means that each time 1 element is skipped take the
  • The step size N denotes that each time N-1 elements are skipped take
  • Negative steps indicate that the reverse is taken (note that the start subscript and end subscript are also marked in reverse)
my_list = [1, 2, 3, 4, 5]
print(my_list[1:4:2])

my_tuple = (0, 1, 2, 3, 4, 5, 6)
print(my_tuple[0:6:2])
str = 'ay, yadang ding small come, nohtyP learn'
new_str = str[::-1]
# print(new_str)
list = new_str.split(',')
print(list[1].replace('Come on', ''))

V. Data container: set (collection)

Definition of set:

# Define collection literals
{element, element, ... , element}
# Define set variables
Variable name = {element, element, ... , element}
# Define the empty set
Variable name = set()

manipulate clarification
set.add(element) Adding an element to a set
collection.remove(element) Removes the specified element from the collection
Set.pop() Remove a random element from the set
Set.clear() Empty the collection
Sets (set 2) Get a new set containing the difference set of the 2 sets
The contents of the original 2 sets remain unchanged
set1.difference_update(set2) In set 1, delete the elements present in set 2
Set 1 is modified, set 2 remains unchanged
Sets (set 2) Get a new set containing all the elements of the 2 sets <br/> the original 2 sets remain unchanged.
len(set) Get an integer that records the number of elements in the set

Characteristics of the set:

  • Can hold multiple data
  • Can hold different types of data (mixed loads)
  • Data is stored unordered (subscript indexes are not supported)
  • Duplicate data is not allowed
  • Can be modified (add or remove elements, etc.)
  • Support for for loops

Example:

my_list = ['111', '222', '333', '111', '333', 'itit', 'hehe', 'itit']
new_set = set()

for val in my_list:
    new_set.add(val)

print(new_set)

VI. Data container: dict (dictionary, mapping)

Dictionary definition: again using {}, but storing the elements one by one: key-value pairs

Attention:

  • Use {} to store primitives, where each element is a key-value pair
  • Each key-value pair contains Key and Value (separated by colons)
  • Use commas to separate key-value pairs
  • Key and Value can be any type of data (key cannot be a dictionary)
  • Key cannot be duplicated, duplication will overwrite the original data.

Tip:

  • Key and Value of a key-value pair can be of any type (Key cannot be a dictionary)
  • Dictionary Key is not allowed to repeat, repeat add equivalent to cover the original data
  • Dictionaries may not be indexed by subscripts; instead, the Value is retrieved by Key.
dic = {
    'King': {
        'Sector': 'Ministry of Science and Technology',
        'Wages': 3000,
        'Level': 1
    },
    'Chow': {
        'Sector': 'Marketing Department',
        'Wages': 5000,
        'Level': 2
    },
    'Lin': {
        'Sector': 'Marketing Department',
        'Wages': 7000,
        'Level': 3
    },
    'Zhang': {
        'Sector': 'Ministry of Science and Technology',
        'Wages': 4000,
        'Level': 1
    },
}

for key in dic:
    if dic[key]['Level'] == 1:
        dic[key]['Level'] += 1
        dic[key]['Wages'] += 1000

print(dic)

To this article about a paper to take you to understand the Python data containers in the article is introduced to this, more related to Python data containers, please search for my previous articles or continue to browse the following related articles I hope you will support me in the future more!