# list

## Definition of list

The list is an ordered collection with no fixed size. It can hold any number of Python objects of any type. The syntax is [element 1, element 2,..., element n].

• The key points are "brackets []" and "commas,"
• Brackets tie all elements together
• Commas separate each element one by one

## List creation

• General list
```x = ['Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday']
print(x, type(x))
# ['Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday'] <class 'list'>

x = [2, 3, 4, 5, 6, 7]
print(x, type(x))
# [2, 3, 4, 5, 6, 7] <class 'list'>
```
• range() create list
```x = list(range(10))
print(x, type(x))
# [0, 1, 2, 3, 4, 5, 6, 7, 8, 9] <class 'list'>

x = list(range(1, 11, 2))
print(x, type(x))
# [1, 3, 5, 7, 9] <class 'list'>

x = list(range(10, 1, -2))
print(x, type(x))
# [10, 8, 6, 4, 2] <class 'list'>
```
• Create list by derivation
```x =  * 5
print(x, type(x))
# [0, 0, 0, 0, 0] <class 'list'>

x = [0 for i in range(5)]
print(x, type(x))
# [0, 0, 0, 0, 0] <class 'list'>

x = [i for i in range(10)]
print(x, type(x))
# [0, 1, 2, 3, 4, 5, 6, 7, 8, 9] <class 'list'>

x = [i for i in range(1, 10, 2)]
print(x, type(x))
# [1, 3, 5, 7, 9] <class 'list'>

x = [i for i in range(10, 1, -2)]
print(x, type(x))
# [10, 8, 6, 4, 2] <class 'list'>

x = [i ** 2 for i in range(1, 10)]
print(x, type(x))
# [1, 4, 9, 16, 25, 36, 49, 64, 81] <class 'list'>

x = [i for i in range(100) if (i % 2) != 0 and (i % 3) == 0]
print(x, type(x))

# [3, 9, 15, 21, 27, 33, 39,
```

Since the element of the list can be any object, what is saved in the list is the pointer to the object. Even if you save a simple [1,2,3], there are 3 pointers and 3 integer objects.
In the x = [a] * 4 operation, only four references to the list are created, so once a changes, the four a in X will also change.

• Create a mixed list
```mix = [1, 'lsgo', 3.14, [1, 2, 3]]
print(mix, type(mix))
# [1, 'lsgo', 3.14, [1, 2, 3]] <class 'list'>
```
• Create an empty list
```empty = []
print(empty, type(empty))  # [] <class 'list'>
```

## Add an element to the list

Unlike tuples, lists are mutable, so append, extend, insert, and remove (POP) operations are available

• list.append(obj) adds a new object at the end of the list and accepts only one parameter. The parameter can be any data type. The appended element maintains the original structure type in the list
• list.extend(seq) appends multiple values in another sequence at one time at the end of the list (expands the original list with the new list)

Strictly speaking, append is an addition that adds an object to the list as a whole, while extend is an extension that adds all elements in an object to the list

• list.insert(index, obj) inserts obj at the index position

## Delete elements from the list

• list.remove(obj) removes the first match of a value in the list
• list.pop([index=-1]) removes an element in the list (the default last element) and returns the value of the element
• del var1[, var2...] Deletes one or more objects
```x = ['Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday']
del x[0:2]
print(x)  # ['Wednesday', 'Thursday', 'Friday']
```

## Gets the element in the list

• Get a single element from the list through the index value of the element. Note that the list index value starts from 0.
• By specifying an index of - 1, Python returns the last list element, an index of - 2 returns the penultimate list element, and so on
The common way to write slices is start: Stop: step
• "Start:" slice from the number start to the end of the list with step as 1 (default).
• ": stop" slice from the list head to the number stop with step as 1 (default)
• "Start: stop" slices from start to stop with step as 1 (default)
• "Start: Stop: step" the specific step is sliced from start to stop. Note that setting step to - 1 in the end is equivalent to reversing the list
• Copy all elements in the list (shallow copy)

## Common operators for lists

• Equal sign operator:==
• Join operator+
• Repeat operator*
• Membership operators in, not in

## Other methods of listing

• list.count(obj) counts the number of times an element appears in the list
```list1 = [123, 456] * 3
print(list1)  # [123, 456, 123, 456, 123, 456]
num = list1.count(123)
print(num)  # 3
```
• list.index(x[, start[, end]]) finds the index position of the first match of a value from the list
```list1 = [123, 456] * 5
print(list1.index(123))  # 0
print(list1.index(123, 1))  # 2
print(list1.index(123, 3, 7))  # 4
```
• list.reverse() reverses the elements in the list
```x = [123, 456, 789]
x.reverse()
print(x)  # [789, 456, 123]
```
• list.sort(key=None, reverse=False) sorts the original list

key – it is mainly used to compare elements. There is only one parameter. The parameters of the specific function are taken from the iteratable object. Specify an element in the iteratable object to sort.
Reverse – collation, reverse = True descending, reverse = False ascending (default).
This method does not return a value, but sorts the objects in the list

```x = [123, 456, 789, 213]
x.sort()
print(x)
# [123, 213, 456, 789]

x.sort(reverse=True)
print(x)
# [789, 456, 213, 123]

# Gets the second element of the list
def takeSecond(elem):
return elem

x = [(2, 2), (3, 4), (4, 1), (1, 3)]
x.sort(key=takeSecond)
print(x)
# [(4, 1), (2, 2), (1, 3), (3, 4)]

x.sort(key=lambda a: a)
print(x)
# [(1, 3), (2, 2), (3, 4), (4, 1)]
```

# tuple

Syntax: (element 1, element 2,..., element n)

• Parentheses bind all elements together
• Commas separate each element one by one

## Create and access a tuple

• Python tuples are similar to lists, except that tuples cannot be modified after they are created, which is similar to strings.
• Tuples use parentheses and lists use square brackets.
• Tuples, like lists, are indexed and sliced with integers
```t1 = (1, 10.31, 'python')
t2 = 1, 10.31, 'python'
print(t1, type(t1))
# (1, 10.31, 'python') <class 'tuple'>

print(t2, type(t2))
# (1, 10.31, 'python') <class 'tuple'>

tuple1 = (1, 2, 3, 4, 5, 6, 7, 8)
print(tuple1)  # 2
print(tuple1[5:])  # (6, 7, 8)
print(tuple1[:5])  # (1, 2, 3, 4, 5)
tuple2 = tuple1[:]
print(tuple2)  # (1, 2, 3, 4, 5, 6, 7, 8)
```
• You can create tuples with parentheses (), or without anything. For readability, it is recommended to use ().
• When a tuple contains only one element, you need to add a comma after the element, otherwise the parentheses will be used as operators.
[example] create a two-dimensional tuple
```x = (1, 10.31, 'python'), ('data', 11)
print(x)
# ((1, 10.31, 'python'), ('data', 11))

print(x)
# (1, 10.31, 'python')
print(x, x, x)
# 1 10.31 python

print(x[0:2])
# (1, 10.31)
```

## Update and delete a tuple

Tuples have immutable properties, so we cannot directly assign values to the elements of tuples. However, as long as the elements in tuples are mutable, we can directly change their elements. Note that this is different from assigning their elements

```t1 = (1, 2, 3, [4, 5, 6])
print(t1)  # (1, 2, 3, [4, 5, 6])

t1 = 9
print(t1)  # (1, 2, 3, [9, 5, 6])
```

## Tuple related operators

• Equal sign operator:==
• Join operator:+
• Repeat operator:*
• Membership operators: in, not in

Tuples can be spliced in two ways, using "plus sign +" and "multiplication sign *". The former is spliced from beginning to end, and the latter is copied

## Built in method

The tuple size and content cannot be changed, so there are only count and index methods

## Decompress tuple

• unpack a one-dimensional tuple (there are several elements, and the left parenthesis defines several variables)
```t = (1, 10.31, 'python')
(a, b, c) = t
print(a, b, c)
# 1 10.31 python
```
• Decompress two-dimensional tuples (define variables according to the tuple structure in tuples)
```t = (1, 10.31, ('OK', 'python'))
(a, b, (c, d)) = t
print(a, b, c, d)
# 1 10.31 OK python
```
• If you only want a few elements of a tuple, use the wildcard "*", which is called wildcard in English. It represents one or more elements in computer language. The following example is to throw multiple elements into the rest variable
```t = 1, 2, 3, 4, 5
a, b, *rest, c = t
print(a, b, c)  # 1 2 5
print(rest)  # [3, 4]
```
• If you don't care about rest variables at all, use the wildcard "*" and underline ""
```t = 1, 2, 3, 4, 5
a, b, *_ = t
print(a, b)  # 1 2
```

# character string

## Definition of string

In Python, a string is defined as a collection of characters between quotation marks.
Python supports the use of paired single or double quotation marks

• Common escape characters in Python
Escape characterdescribe
\\Backslash symbol
'Single quotation mark
"Double quotation mark
\nLine feed
\tHorizontal tab
\renter

The original string only needs to be preceded by an English letter r

```print(r'C:\Program Files\Intel\Wifi\Help')
# C:\Program Files\Intel\Wifi\Help
```

Three quotation marks allow a string to span multiple lines. The string can contain line breaks, tabs and other special characters

## Slicing and splicing of strings

• Similar to tuples, it is immutable
• Slices are usually written in the form of start:end, including the elements corresponding to the "start index" and excluding the elements corresponding to the "end index".
• The index value can be positive or negative, and the positive index starts from 0, from left to right; The negative index starts from - 1, right to left. When a negative index is used, the count starts from the last element. The position number of the last element is - 1.
```str1 = 'I Love LsgoGroup'
print(str1[:6])  # I Love
print(str1)  # e
print(str1[:6] + " Inserted string " + str1[6:])
# I Love inserted string LsgoGroup

s = 'Python'
print(s)  # Python
print(s[2:4])  # th
print(s[-5:-2])  # yth
print(s)  # t
print(s[-1])  # n
```

## Common built-in methods for string

• capitalize() converts the first character of a string to uppercase
• lower() converts all uppercase characters in the string to lowercase.
• upper() converts lowercase letters in a string to uppercase.
• swapcase() converts uppercase to lowercase and lowercase to uppercase in the string.
• count(str, beg= 0,end=len(string)) returns the number of occurrences of str in the string. If beg or end is specified, it returns the number of occurrences of str in the specified range
• Endswitch (suffix, beg = 0, end = len (string)) checks whether the string ends with the specified substring suffix. If yes, it returns True; otherwise, it returns False. If beg and end specify values, check within the specified range.
• Startswitch (substr, beg = 0, end = len (string)) checks whether the string starts with the specified substr. If yes, it returns True; otherwise, it returns False. If beg and end specify values, check within the specified range
• find(str, beg=0, end=len(string)) checks whether str is included in the string. If the specified range is beg and end, check whether it is included in the specified range. If it is included, return the starting index value, otherwise return - 1.
• rfind(str, beg=0,end=len(string)) is similar to the find() function, but it starts from the right
• isnumeric() returns True if the string contains only numeric characters, otherwise False
• ljust(width[, fillchar]) returns a left aligned original string and fills the new string with fillchar (default space) to the length width.
• rjust(width[, fillchar]) returns a right aligned original string and fills the new string with fillchar (default space) to the length width
• lstrip([chars]) truncates the space or specified character to the left of the string.
• rstrip([chars]) deletes spaces or specified characters at the end of a string.
• strip([chars]) executes lstrip() and rstrip() on a string
• partition(sub) finds the substring sub and divides the string into a triple (pre_sub,sub,fol_sub). If the string does not contain sub, it returns ('original string ',', ').
• rpartition(sub) is similar to the partition() method, but it starts from the right
• replace(old, new [, max]) replaces old in the string with new. If max is specified, the replacement shall not exceed max times
• split(str="", num) has no parameters. The default is to slice strings with spaces as separators. If the num parameter is set, only num substrings will be separated and a list of spliced substrings will be returned
• Splitlines ([keepers]) are separated by lines ('\ r', '\ r\n', \ n ') and return a list containing lines as elements. If the parameter keepers is False, it does not contain line breaks. If it is True, it retains line breaks
• Aketrans (intra, outtab) creates a character mapping conversion table. The first parameter is a string, which represents the characters to be converted, and the second parameter is also a string, which represents the target of conversion.
• translate(table, deletechars = "") convert the characters of the string according to the table given by the parameter table, and put the characters to be filtered into the deletechars parameter

## String formatting

• format formatting function
```str8 = "{0} Love {1}".format('I', 'Lsgogroup')  # Position parameters
print(str8)  # I Love Lsgogroup

str8 = "{a} Love {b}".format(a='I', b='Lsgogroup')  # Keyword parameters
print(str8)  # I Love Lsgogroup

str8 = "{0} Love {b}".format('I', b='Lsgogroup')  # The location parameter should precede the keyword parameter
print(str8)  # I Love Lsgogroup

str8 = '{0:.2f}{1}'.format(27.658, 'GB')  # Keep two decimal places
print(str8)  # 27.66GB
```
• Python string formatting symbol
Symboldescribe
%cFormatted characters and their ASCII codes
%sFormat the string and process the object with the str() method
%rFormat the string and process the object with the rper() method
%dFormat integer
%oFormat unsigned octal number
%XFormat unsigned hexadecimal number (upper case)
%fFormat floating-point numbers to specify the precision after the decimal point
%eFormatting floating point numbers with scientific counting
%EThe function is the same as%e, format floating-point numbers with scientific counting method
%gUse% f or% e depending on the size of the value
%GThe function is the same as% g. use% f or% E according to the size of the value
• Formatting operator helper
Symbolfunction
m.nm is the minimum total width of the display and n is the number of digits after the decimal point (if available)
-Use as left alignment
+Displays a plus sign (+) before a positive number
#Zero ('0 ') is displayed in front of octal numbers and' 0x 'or' 0x 'is displayed in front of hexadecimal numbers (depending on whether' x 'or' x 'is used)
0The displayed number is preceded by '0' instead of the default space

# Dictionaries

## Variable type and immutable type

• Sequences are indexed by consecutive integers. The difference is that dictionaries are indexed by "Keywords". Keywords can be any immutable type, usually strings or numeric values.
• Dictionary is the only mapping type in Python. String, tuple and list belong to sequence type
How to quickly determine whether a data type X is a variable type? Two methods
1. Troublesome method: use the id(X) function to perform some operation on X and compare the IDS before and after the operation. If they are different, X is not variable. If they are the same, X is variable
2. Convenient method: use hash(X) to prove that X can be hashed, that is, it is immutable, and vice versa

## Definition of dictionary

The dictionary is an unordered set of key:value pairs. The keys must be different from each other (within the same dictionary)

• The internal storage order of dict has nothing to do with the order in which key s are placed.
• dict is extremely fast in searching and inserting. It will not increase with the increase of key s, but it needs a lot of memory
The dictionary definition syntax is {element 1, element 2,..., element n}
• Each element is a "key value pair" -- key: value
• The key points are braces {}, commas, and colons
• Braces – tie all elements together
• Comma – separate each key value pair
• Colon – separates the key from the value

## Create and access Dictionaries

```brand = ['Li Ning', 'Nike', 'Adidas']
slogan = ['Anything is possible', 'Just do it', 'Impossible is nothing']
print('Nike's slogan is:', slogan[brand.index('Nike')])
# Nike's slogan is: Just do it

dic = {'Li Ning': 'Anything is possible', 'Nike': 'Just do it', 'Adidas': 'Impossible is nothing'}
print('Nike's slogan is:', dic['Nike'])
# Nike's slogan is: Just do it
```

Create a dictionary using a string or numeric value as a key

```dic1 = {1: 'one', 2: 'two', 3: 'three'}
print(dic1)  # {1: 'one', 2: 'two', 3: 'three'}
print(dic1)  # one
print(dic1)  # KeyError: 4
```

If the selected key does not exist in the dictionary, an error KeyError will be reported directly

• dict() creates an empty dictionary

The data is directly put into the dictionary through the key, but a key can only correspond to one value. If you put value into a key multiple times, the subsequent value will flush out the previous value

```dic = dict()
dic['a'] = 1
dic['b'] = 2
dic['c'] = 3

print(dic)
# {'a': 1, 'b': 2, 'c': 3}

dic['a'] = 11
print(dic)
# {'a': 11, 'b': 2, 'c': 3}

dic['d'] = 4
print(dic)
# {'a': 11, 'b': 2, 'c': 3, 'd': 4}
```
• dict(mapping)
```dic1 = dict([('apple', 4139), ('peach', 4127), ('cherry', 4098)])
print(dic1)  # {'cherry': 4098, 'apple': 4139, 'peach': 4127}

dic2 = dict((('apple', 4139), ('peach', 4127), ('cherry', 4098)))
print(dic2)  # {'peach': 4127, 'cherry': 4098, 'apple': 4139}
```
• dict(**kwargs)
```dic = dict(name='Tom', age=10)
print(dic)  # {'name': 'Tom', 'age': 10}
print(type(dic))  # <class 'dict'>
```

## Built in method of dictionary

• dict.fromkeys(seq[, value]) is used to create a new dictionary. The elements in seq sequence are used as dictionary keys. Value is the initial value corresponding to all keys in the dictionary
• dict.keys() returns an iteratable object. You can use list() to convert it into a list. The list is all the keys in the dictionary
• dict.values() returns an iterator that can be converted into a list using list(), which is all the values in the dictionary
• dict.items() returns an array of traversable (key, value) tuples in a list
• dict.get(key, default=None) returns the value of the specified key. If the value is not in the dictionary, it returns the default value
• dict.setdefault(key, default=None) is similar to the get() method. If the key does not exist in the dictionary, the key will be added and the value will be set as the default value
```dic = {'Name': 'Lsgogroup', 'Age': 7}
print("Age The value of the key is : %s" % dic.setdefault('Age', None))  # The value of the Age key is: 7
print("Sex The value of the key is : %s" % dic.setdefault('Sex', None))  # The value of the Sex key is: None
print(dic)
# {'Age': 7, 'Name': 'Lsgogroup', 'Sex': None}
```
• The key in dict in operator is used to determine whether the key exists in the dictionary. If the key is in the dictionary dict, it returns true; otherwise, it returns false. On the contrary, if the key returns false in dict, otherwise it returns true
• dict.pop(key[,default]) deletes the value corresponding to the key given in the dictionary, and the return value is the deleted value. The key value must be given. If the key does not exist, the default value is returned.
• del dict[key] deletes the value corresponding to the key given in the dictionary
• dict.popitem() randomly returns and deletes a pair of keys and values in the dictionary. If the dictionary is empty but this method is called, a KeyError exception is reported
• dict.clear() is used to delete all elements in the dictionary
• dict.copy() returns a shallow copy of a dictionary
• dict.update(dict2) updates the key:value pair of the dictionary parameter dict2 to the dictionary dict

# aggregate

Similar to dict, set in Python is also a set of keys, but does not store value. Since keys cannot be repeated, there are no duplicate keys in set.

Note that the key is an immutable type, that is, the hash value

characteristic
Unordered and unique

```num = {}
print(type(num))  # <class 'dict'>
num = {1, 2, 3, 4}
print(type(num))  # <class 'set'>
```

## Creation of collections

• Create objects before adding elements
• Only s = set() can be used when creating an empty collection, because s = {} creates an empty dictionary
• Directly enclose a pile of elements in curly braces {element 1, element 2,..., element n}
• Duplicate elements are automatically filtered in the set
• Use the set(value) factory function to convert a list or tuple into a set

Because set stores an unordered set, we cannot create an index or perform slice operations for the set, and there are no keys to obtain the values of elements in the set, but we can judge whether an element is in the set

## Accessing values in a collection

• You can use the len() built-in function to get the size of the collection
```s = set(['Google', 'Baidu', 'Taobao'])
print(len(s))  # 3
```
• You can use for to read the data in the collection one by one
```s = set(['Google', 'Baidu', 'Taobao'])
for item in s:
print(item)

# Baidu
# Taobao
```
• You can judge whether an element already exists in the collection by in or not in
```s = set(['Google', 'Baidu', 'Taobao'])
print('Taobao' in s)  # True
print('Facebook' not in s)  # True
```

## Built in methods for collections

• set.add(elmnt) is used to add elements to the collection. If the added elements already exist in the collection, no operation will be performed
• set.update(set) is used to modify the current set. You can add a new element or set to the current set. If the added element already exists in the set, the element will only appear once, and the repeated elements will be ignored
• set.remove(item) is used to remove the specified element from the collection. If the element does not exist, an error occurs
• set.discard(value) is used to remove the specified set element. The remove() method will cause an error when removing a non-existent element, while the discard() method will not
• set.pop() is used to randomly remove an element

Because set is an unordered and non repeating set, two or more sets can do set operations in a mathematical sense

• set.intersection(set1, set2) returns the intersection of two sets.
• Set1 & set2 returns the intersection of two sets.
• set.intersection_update(set1, set2) intersection to remove non overlapping elements from the original set
• set.union(set1, set2) returns the union of two sets.
• set1 | set2 returns the union of two sets
• set.difference(set) returns the difference set of the set.
• set1 - set2 returns the difference set of the set.
• set.difference_update(set) is the difference set of the set. The element is directly removed from the original set without return value
• set.symmetric_difference(set) returns the XOR of the set.
• set1 ^ set2 returns the XOR of the set.
• set.symmetric_difference_update(set) removes the same elements in another specified set in the current set, and inserts different elements in another specified set into the current set
• set.issubset(set) determines whether the set is contained by other sets. If yes, it returns True; otherwise, it returns False.
• Set1 < = set2 determines whether the set is contained by other sets, - if yes, it returns True; otherwise, it returns False
• set.issuperset(set) is used to judge whether the set contains - other sets. If yes, it returns True; otherwise, it returns - False.
• Set1 > = set2 determines whether the set contains other sets. If so, it returns True; otherwise, it returns False
• set.isdisjoint(set) is used to judge whether two sets do not intersect. If yes, it returns True; otherwise, it returns False

## Conversion of sets

```se = set(range(4))
li = list(se)
tu = tuple(se)

print(se, type(se))  # {0, 1, 2, 3} <class 'set'>
print(li, type(li))  # [0, 1, 2, 3] <class 'list'>
print(tu, type(tu))  # (0, 1, 2, 3) <class 'tuple'>
```

## Immutable set

Python provides an implementation version that cannot change the collection of elements, that is, elements cannot be added or deleted. The type is called frozenset. It should be noted that frozenset can still perform collection operations, but the method with update cannot be used.

• frozenset([iterable]) returns a frozen collection. After freezing, no elements can be added or deleted from the collection.
```a = frozenset(range(10))  # Generate a new immutable set
print(a)
# frozenset({0, 1, 2, 3, 4, 5, 6, 7, 8, 9})

b = frozenset('lsgogroup')
print(b)
# frozenset({'g', 's', 'p', 'r', 'u', 'o', 'l'})
```

# sequence

In Python, sequence types include string, list, tuple, set and dictionary. These sequences support some general operations, but in particular, set and dictionary do not support index, slice, addition and multiplication operations

## Built in functions for sequences

• list(sub) converts an iteratable object into a list
```a = list()
print(a)  # []

b = 'I Love LsgoGroup'
b = list(b)
print(b)
# ['I', ' ', 'L', 'o', 'v', 'e', ' ', 'L', 's', 'g', 'o', 'G', 'r', 'o', 'u', 'p']

c = (1, 1, 2, 3, 5, 8)
c = list(c)
print(c)  # [1, 1, 2, 3, 5, 8]
```
• tuple(sub) converts an iteratable object into a tuple
```a = tuple()
print(a)  # ()

b = 'I Love LsgoGroup'
b = tuple(b)
print(b)
# ('I', ' ', 'L', 'o', 'v', 'e', ' ', 'L', 's', 'g', 'o', 'G', 'r', 'o', 'u', 'p')

c = [1, 1, 2, 3, 5, 8]
c = tuple(c)
print(c)  # (1, 1, 2, 3, 5, 8)
```
• str(obj) converts obj objects to strings
```a = 123
a = str(a)
print(a)  # 123
```
• len(s) returns the length of an object (character, list, tuple, etc.) or the number of elements
• s – object
```a = list()
print(len(a))  # 0

b = ('I', ' ', 'L', 'o', 'v', 'e', ' ', 'L', 's', 'g', 'o', 'G', 'r', 'o', 'u', 'p')
print(len(b))  # 16

c = 'I Love LsgoGroup'
print(len(c))  # 16
```
• max(sub) returns the maximum value in the sequence or parameter set
```print(max(1, 2, 3, 4, 5))  # 5
print(max([-8, 99, 3, 7, 83]))  # 99
print(max('IloveLsgoGroup'))  # v
```
• min(sub) returns the minimum value in the sequence or parameter set
```print(min(1, 2, 3, 4, 5))  # 1
print(min([-8, 99, 3, 7, 83]))  # -8
print(min('IloveLsgoGroup'))  # G
```
• sum(iterable[, start=0]) returns the sum of the sequence iterable and the optional parameter start
```print(sum([1, 3, 5, 7, 9]))  # 25
print(sum([1, 3, 5, 7, 9], 10))  # 35
print(sum((1, 3, 5, 7, 9)))  # 25
print(sum((1, 3, 5, 7, 9), 20))  # 45
```
• sorted(iterable, key=None, reverse=False) sorts all iteratable objects
• Iteratable – iteratable object.
• key – it is mainly used to compare elements. There is only one parameter. The parameters of the specific function are taken from the iteratable object. Specify an element in the iteratable object to sort.
• Reverse – collation, reverse = True descending, reverse = False ascending (default).
• Returns a reordered list
```x = [-8, 99, 3, 7, 83]
print(sorted(x))  # [-8, 3, 7, 83, 99]
print(sorted(x, reverse=True))  # [99, 83, 7, 3, -8]

t = ({"age": 20, "name": "a"}, {"age": 25, "name": "b"}, {"age": 10, "name": "c"})
x = sorted(t, key=lambda a: a["age"])
print(x)
# [{'age': 10, 'name': 'c'}, {'age': 20, 'name': 'a'}, {'age': 25, 'name': 'b'}]
```
• The reversed(seq) function returns an inverted iterator
• seq – the sequence to be converted, which can be tuple, string, list or range
```s = 'lsgogroup'
x = reversed(s)
print(type(x))  # <class 'reversed'>
print(x)  # <reversed object at 0x000002507E8EC2C8>
print(list(x))
# ['p', 'u', 'o', 'r', 'g', 'o', 'g', 's', 'l']

t = ('l', 's', 'g', 'o', 'g', 'r', 'o', 'u', 'p')
print(list(reversed(t)))
# ['p', 'u', 'o', 'r', 'g', 'o', 'g', 's', 'l']

r = range(5, 9)
print(list(reversed(r)))
# [8, 7, 6, 5]

x = [-8, 99, 3, 7, 83]
print(list(reversed(x)))
# [83, 7, 3, 99, -8]
```
• enumerate(sequence, [start=0]) is used to combine a traversable data object (such as list, tuple or string) into an index sequence, and list data and data subscripts at the same time. It is generally used in the for loop
```seasons = ['Spring', 'Summer', 'Fall', 'Winter']
a = list(enumerate(seasons))
print(a)
# [(0, 'Spring'), (1, 'Summer'), (2, 'Fall'), (3, 'Winter')]

b = list(enumerate(seasons, 1))
print(b)
# [(1, 'Spring'), (2, 'Summer'), (3, 'Fall'), (4, 'Winter')]

for i, element in a:
print('{0},{1}'.format(i, element))
# 0,Spring
# 1,Summer
# 2,Fall
# 3,Winter
```
• zip(iter1 [,iter2 [...]])
• It is used to take the iteratable object as a parameter, package the corresponding elements in the object into tuples, and then return the object composed of these tuples. The advantage of this is to save a lot of memory.
• You can use the list() transformation to output the list.
• If the number of elements of each iterator is inconsistent, the length of the returned list is the same as that of the shortest object. The tuple can be decompressed into a list by using the * operator.
```a = [1, 2, 3]
b = [4, 5, 6]
c = [4, 5, 6, 7, 8]

zipped = zip(a, b)
print(zipped)  # <zip object at 0x000000C5D89EDD88>
print(list(zipped))  # [(1, 4), (2, 5), (3, 6)]
zipped = zip(a, c)
print(list(zipped))  # [(1, 4), (2, 5), (3, 6)]

a1, a2 = zip(*zip(a, b))
print(list(a1))  # [1, 2, 3]
print(list(a2))  # [4, 5, 6]
```

Tags: Python data structure

Posted on Wed, 20 Oct 2021 02:44:37 -0400 by billiondevil