This article introduces the list and tuples in python in detail for general operations: indexing, sharding, addition, multiplication, checking whether an element belongs to a sequence member, length, minimum value, and maximum value.
Example:
Numbers = [100, 34, 67] len (numbers) # returns 3max (numbers) # returns min (numbers) # returns 34
List:
1. list function
>>>list('Hello')['H','e','l','l','o']
* You can use join (for example, ''. join (somelist) to convert the list to a string.
2. list operations
Element assignment:
>>>x=[1,2,3]>>>x[1]=4>>>x[1,4,3]
Delete element:
>>>x=['abc','def','ghi','jk']>>>del x[2]>>>x['abc','def','jk']
Partition assignment:
>>>x=list('Happy')>>>name['H','a','p','p','y']>>>x[1:]=list('ello')>>>x['H','e','l','l','o']
3. list method:
Append
>>>x=[1,2,3]>>>x.append(4)>>>x[1,2,3,4]
Count
>>>x=[1,2,3,1,3,5,5]>>>x.count(3)2
Extend
>>>a=[1,1]>>>b=[2,3]>>>a.extend(b)>>>a[1,1,2,3]
Index
>>>x=['a','b','c']>>>x.index('b')1
Insert element
>>>x=[1,2,3]>>>x.insert(2,'a')>>>x[1,2,'a',3]
Pop removes the list element (the last one by default)
>>> x=[1,2,3,4]>>> x.pop()4>>> x.pop(1)2>>> x[1, 3]
Remove the first match for a value in the list
>>> x=['my','to','is','she','to']>>> x.remove('to')>>> x['my', 'is', 'she', 'to']
Reverse stores the elements in the list in reverse order
>>> x=[1,2,3]>>> x.reverse()>>> x[3, 2, 1]
>>> x=[1,2,3]>>> list(reversed(x))[3, 2, 1]>>> x[1, 2, 3]
Sort is used to sort the list in the original position
>>> x=[4,6,2,1,7,8,3]>>> x.sort()>>> x[1, 2, 3, 4, 6, 7, 8]>>> x=[4,6,2,1,7,8,3]>>> y=sorted(x)>>> x[4, 6, 2, 1, 7, 8, 3]>>> y[1, 2, 3, 4, 6, 7, 8]>>> x=[3,2,1]>>> y=x>>> y.sort()>>> x[1, 2, 3]>>> y[1, 2, 3]
>>> Sorted ('Hello ')
['E', 'H', 'L', 'L', 'O']
Tuples: unchangeable sequence
>>> 1, 2, 3 (1, 2, 3) >>> (1, 2, 3) (1, 2, 3) >>> () # empty tuples () >>> 1, SyntaxError: invalid syntax >>>> 1, (1,) >>> 1, # The ancestor must have a comma (1,) >>> 3*(40 + 2,) (42, 42, 42)
The tuple function converts a sequence to a metagroup.
>>> tuple([3,2,1])(3, 2, 1)>>> tuple('abc')('a', 'b', 'c')
Reasons for the substitution of tuples
The above is a detailed description of the list and tuples in python. For more information, see other related articles in the first PHP community!