Python lists and tuples detail examples

  • 2020-04-02 13:14:22
  • OfStack

This chapter introduces the concept of data structures. A data structure is a collection of data elements that are organized together in some way. In python, the most basic data structure is a sequence. Each element in a sequence is assigned an ordinal number, the position of the element, also known as an index. Note: the first index is 0.
1. Sequence overview
Python has six built-in sequences: lists, tuples, strings, Unicode strings, buffer objects, and xrange objects.
  The emphasis here is on lists and tuples. The main difference between lists and tuples is that lists can be modified and tuples cannot. In general, the following tables can replace tuples in almost all cases.
Sequences are useful when you need to manipulate a set of values:


Edward = ["Gumby",42]

  At the same time, sequences can contain other sequences. Such as:

Edward = ["Gumby",42]
John = ["Smith",50]
database = [Edward,John]

2. General sequence operation
All sequence types can perform certain operations, including indexing, sharding, adding, multiplying, and checking whether an element is a member of a sequence (membership). In addition, python also calculates the sequence length and finds the built-in functions for the largest and smallest elements.
2.1 the index
All the elements in the sequence are numbered -- increments from 0. These elements can be accessed individually by number:

>>>greeting = "hello"
>>>greeting[0]
'H'

With a negative index, python counts from the right, that is, from the last element, whose position number is -1!

>>> greeting[-1]
'g'

2.2 shard
Sharding provides access to a range of elements, with two indexes separated by colons. Sharding is useful for extracting part of a sequence, the first index is the first element number of the extracted part, and the last index is the first element number of the remaining part after sharding.

>>> number = [1,2,3,4,5,6,7,8,9,10]
>>> number[3:6]
[4,5,6]
>>> number[0:1]
[1]

2.2.1 elegant shortcuts
To access the last three elements, you can do this explicitly:

>>> number[7:10]
[8,9,10]

Here the 11th element that the index 10 points to does not exist, but is after the last element.
If you need to count from the end of the list, that is, if the sharding part includes the elements at the end of the sequence, then you only need to empty the last index:

>>> number[-3:]
[8,9,10]

This method applies to elements at the beginning of a sequence or to displaying the entire sequence:

>>> number[:3]
[1,2,3]
>>> number[:]
[1,2,3,4,5,6,7,8,9,10]

2.2.2 larger step size
When sharding occurs, both the start and end of the sharding need to be specified. Another parameter, step size, is usually set implicitly. The default step size is 1. If you display a number with a step size greater than 1, some elements are skipped.

>>> number[0:10:2]
[1,3,5,7,9]
>>> number[3:6:3]
[4]

The step size cannot be 0, but it can be negative, that is, the element can be extracted from right to left:

>>> number[10:0:-2]
[10,8,6,4,2]
>>> number[0:10:-2]
[]

The second one above is wrong. When you use a negative number as the step size, you have to make the starting point bigger than the ending point.
2.3 sequence addition
Sequence concatenation can be performed by using the plus sign:

>>> [1,2,3] + [4,5,6]
[1,2,3,4,5,6]
>>>'hello, ' + 'world'
'hello, world'
>>>[1,2,3] + 'hello'
TypeError:can only concatenate list(not 'string') to list

As shown in the third example above, lists and strings cannot be concatenated together; although they are both sequences, only two sequences of the same type can be concatenated.

2.4  The multiplication 
 Using a digital x Multiplying by a sequence produces a new sequence, in which the original sequence is repeated x Time: 
[code]
>>> 'python' *5
'pythonpythonpythonpythonpython'
>>> [42] * 5
[42,42,42,42,42]

None, empty list and initialization
An empty list can be represented by two brackets ([]), but if we want to create a list of ten elements without any useful content, we need a value to represent the empty value. We can do this:

>>> sequence = [None] * 10
>>> sequence 
[None,None,None,None,None,None,None,None,None,None]

2.5 membership
To check whether a value is in a sequence, use the in operator. It checks if a condition is True and returns the corresponding value (True or False)

>>> p = 'write'
>>> 'w' in p
True
>>> user =["a","b","c"]
>>> raw_input('Enter:') in user
Enter:a
True

2.6 length, maximum and minimum

>>> numbers = [10,20,30]
>>> len(numbers)
>>> max(numbers)
>>> min(numbers)
>>> max(1,99)
>>> min(1,99)

In the last two examples above, the parameters of the Max and min functions are not sequences, but take multiple Numbers as parameters directly.
3. List: python's "coolies"
3.1 the list function
Because strings cannot be modified like lists, it is sometimes useful to create lists based on strings. Ps: the list function applies to all types of lists, not just strings.

>>> list('hello')
['h','e','l','l','o']

Tip: you can convert a list of characters to a string using the following expression:

>>> strs =  '  '.jion ( list ) 
>>> strs
"h e l l o"

3.2 basic list operations
A method is a function that is closely related to some object, such as a list, number, string, or other type of object. The list provides several methods for detecting or modifying its contents.
  3.2.1 append
The append method is used to append a new object to the end of the list:

>>> lst = [1,2,3]
>>> lst.append(4)
>>> lst
[1,2,3,4]

Note: the append method does not simply return a new list that has been modified, but directly modifies the original list.

3.2.2 the count
The count method counts the number of times an element appears in the list:

>>> x =[[1,2],1,1,[1,2,[1,2]]]
>>> x.count(1)
2

3.2.3 the extend
The extend method can append multiple values from another sequence at once at the end of a list.
Note: the main difference between the extend method and the join operation (+) is that the extend method modifies the extended sequence, while the join operation returns a whole new list.

3.2.4 index
The index method is used to find the index position of the first match of a value in the list:

>>> knights = ['we','are','the','knights']
>>> knights.index('the')
2
>>> knights.index("hi")
ValueError:list.index(x):x not in list

When a match is not found, an exception is thrown.

3.2.5 insert
The insert method is used to insert objects into a list:

>>> numbers = [1,2,3,6]
>>> numbers = insert(3,5)
>>> numbers
[1,2,3,5,6]
>>> numbers[3:3] = [4]
>>> numbers
[1,2,3,4,5,6]

In the last example above, inserts are implemented by sharding assignments, but not as readable as inserts.

3.2.6 pop
The pop method removes an element from the list and returns its value. It is the only list method that can modify the list and return its value:

>>> x = [1,2,3]
>>> x.pop()
3
>>> x
[1,2]

3.2.7 remove
  The remove method is used to remove the first match of a value in the list:

>>> x = ['to','be','to']
>>> x.remove('to')
>>> x
['be','to']
>>> x.remove('kkk')
ValueError:list.remove(x):x not in list

You can see that only values that appear for the first time are removed, and values that are not in the list are not removed.

  3.2.8 reverse
The reverse method stores the elements in the list in reverse:

>>> x = [1,2,3]
>>> x.reverse()
>>> x
[3,2,1]

  3.2.9 sort
The sort method is used to sort a list in its original position, meaning to change the original list rather than simply returning a sorted copy of the list.
If you want to get a sort without changing the original value, you need to assign the value before sorting:

>>> x = [4,2,7,1]
>>> y = x[:]
>>> y.sort()
>>> x
[4,2,7,1]
>>>y
[1,2,4,7]

Note: the above example USES y=x[:] for the assignment. Sharding is an efficient way to copy an entire list. If you simply assign x to y, there is no (y=x), because that makes x and y point to the same list.
Another way to get a copy of the sorted list is to use the sorted function:

>>> x = [4,5,3,7,2]
>>> y = sorted(x)
>>> x
[4,5,3,7,2]
>>> y
[2,3,4,5,7]
 

  3.2.10 advanced sort
If you want the elements to be sorted in a particular way, you can customize the comparison function in the form of compare(x,y). The built-in CMP function provides the default implementation of the comparison function:

>>> cmp(1,2)
-1
>>> cmp(2,1)
>>> cmp(1,1)
>>> numbers = [5,3,9,7]
>>> numbers.sort(cmp)
>>> numbers 
[3,5,7,9]

The sort method has two other optional arguments -key and reverse. To use them, you specify them by name.

>>> x = ['a','abc','ab']
>>> x.sort(key=len)
>>> x
['a','ab','abc']
>>> y = [2,4,1,5]
>>> y.sort(reverse)
>>> y
[5,4,2,1]


  4. Tuples: immutable sequences
  The syntax for creating tuples is simple: if you separate values with commas, you automatically create tuples.

>>>1,2,3
(1,2,3)
>>>(1,2,3)
(1,2,3)
>>>()
()
>>>42,
(42,)

As in the last example above, if you want to implement a tuple with a value, you must add a comma after the value.
4.1 the tuple function
Tuple takes a sequence as an argument and converts it to a tuple. If the argument is a tuple, the argument is returned as is:

>>> tuple([1,2,3])
(1,2,3)
>>> tuple('abc')
('a','b','c')
>>> tuple((1,2,3))
(1,2,3)

4.2 basic tuple operations
Tuples aren't complicated, and there's not much more to do than create tuples and access to tuple elements:

>>>x = 1,2,3
>>>x[1]
2
>>> x[0:2]
(1,2)

A slice of a tuple is still a tuple, just as a slice of a list is still a list.

4.3 so what's the point
Tuples are irreplaceable:
(1) tuples can be used as keys in maps, not lists.
(2) tuples exist as return values of many built-in functions and methods.

 


Related articles: