Examples of Python lists and tuples _python

Source: Internet
Author: User
Tags data structures extend in python

In this chapter, the concept of data structure is introduced. Data structures are collections of elements that are organized together in some way. In Python, the most basic data structure is the sequence. Each element in the sequence is assigned an ordinal number, that is, the position of the element, also known as the index. Note: The first index is 0.
1. Sequence Overview
Python has 6 types of built-in sequences: lists, tuples, strings, Unicode strings, buffer objects, and Xrange objects.
Here you will focus on lists and tuples. The main difference between a list and a tuple is that the list can be modified and the tuple cannot be modified. In general, lists can be substituted for tuples in almost all cases.
The sequence works well when you need to manipulate a set of values:

Copy Code code as follows:

Edward = ["Gumby", 42]

Also, a sequence can contain other sequences. Such as:
Copy Code code as follows:

Edward = ["Gumby", 42]
John = ["Smith", 50]
Database = [Edward,john]

2. General sequence operation
All sequence types can operate on certain characteristics, including indexing, partitioning, adding, multiplying, and checking whether an element belongs to a member of a sequence (membership). In addition, Python has a sequence length to find the built-in function of the maximum element and the smallest element.
2.1 Index
All the elements in the sequence are numbered-incremented from 0 onwards. These elements can be accessed individually by number:
Copy Code code as follows:

>>>greeting = "Hello"
>>>GREETING[0]
H

With a negative index, Python will start counting from the right side, which is the last element, and the last element's position number is-1!
Copy Code code as follows:

>>> Greeting[-1]
' G '

2.2 Slice
A fragment can access a range of elements and is implemented by 2 indexes separated by colons. Fragmentation is useful for extracting part of a sequence, the first index is the first element number of the extraction section, and the last index is the first element number of the remainder after the fragment.
Copy Code code as follows:

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

The 2.2.1 Elegant shortcut
You need access to the last 3 elements, so you can explicitly manipulate:
Copy Code code as follows:

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

The 11th element that the index 10 points to does not exist, but is after the last element.
If you need to start counting from the end of the list, that is, if the fragment portion includes the element at the end of the sequence, then just empty the last index:
Copy Code code as follows:

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

This method applies to elements that begin the sequence or to display the entire sequence:
Copy Code code as follows:

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

2.2.2 Larger step size
At the time of fragmentation, the beginning and end of the fragment are to be specified, and the other parameter-step, usually implicitly set. The default step size is 1. If the display set step size is larger than 1, then some elements are skipped.
Copy Code code as follows:

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

The step size cannot be 0, but can be a negative number, that is, to extract the element from right to left:
Copy Code code as follows:

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

The second formula above is wrong, and when you use a negative number as a step, you must make the start point larger than the end point.
2.3 Sequence Addition
You can perform sequential connection operations by using the plus sign:
Copy Code code as follows:

>>> [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 connected to one another, although they are all sequences, but only 2 sequences of the same type can be connected.
Copy Code code as follows:

2.4 Multiplication
Multiplying the number x by a sequence produces a new sequence in which the original sequence is repeated x times:
[Code]
>>> ' python ' *5
' Pythonpythonpythonpythonpython '
>>> [42] * 5
[42,42,42,42,42]

None, empty list and initialization
An empty list can be represented by 2 brackets ([]), but if you want to create a list that occupies 10 element space without any useful content, we need a value to represent the null value, and you can do this:
Copy Code code as follows:

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

2.5 Member Qualifications
In order to check whether a value is in a sequence, you can use the in operator. It checks to see if a condition is true, and then returns the corresponding value (TRUE or FALSE)
Copy Code code as follows:

>>> p = ' Write '
>>> ' W ' in P
True
>>> user =["A", "B", "C"]
>>> raw_input (' Enter: ') in user
Enter:a
True

2.6 length, maximum minimum value
Copy Code code as follows:

>>> numbers = [10,20,30]
>>> Len (Numbers)
>>> Max (Numbers)
>>> min (Numbers)
>>> Max (1,99)
>>> min (1,99)

In the last 2 examples above, the parameters of the Max function and the Min function are not sequences, but are directly parameters with multiple numbers.
3. List: Python's "coolie"
3.1 List function
Because strings cannot be modified like lists, it is sometimes useful to create lists from strings. The Ps:list function applies to all types of lists, not just strings.
Copy Code code as follows:

>>> list (' Hello ')
[' H ', ' e ', ' l ', ' l ', ' O ']

Tip: You can use the following expression to convert a list of characters into a string:
Copy Code code as follows:

>>> STRs = '. Jion (list)
>>> STRs
"H e l l o"

3.2 Basic list operations
A method is a function that has a close relationship with some objects, possibly a list, a number, or a string or other type of object. The list provides several methods for detecting or modifying the contents of the.
3.2.1 Append
The Append method is used to append a new object at the end of the list:
Copy Code code as follows:

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

Note: The Append method does not simply return a modified new list, but instead directly modifies the original list.

3.2.2 Count
The Count method counts the number of times an element appears in the list:
Copy Code code as follows:

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

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

3.2.4 Index
The index method is used to find out where the first occurrence of a value is indexed from the list:
Copy Code code as follows:

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

An exception is thrown when a match is not found.

3.2.5 Insert
The Insert method is used to insert an object into the list:
Copy Code code as follows:

>>> 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 through a fragment assignment, but the readability is not as good as the insert.

3.2.6 Pop
The Pop method removes an element from the list and returns the value of the element, which is the only list method that can modify the list and return the element value:
Copy Code code as follows:

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

3.2.7 Remove
The Remove method removes the first occurrence of a value in the list:
Copy Code code as follows:

>>> x = [' To ', ' is ', ' to ']
>>> x.remove (' to ')
>>> x
[' Being ', ' to ']
>>> x.remove (' KKK ')
ValueError:list.remove (x): X not in List

You can see that only the first occurrence of the value is removed, and the value not in the list will not be removed.

3.2.8 Reverse
The reverse method stores the elements in the list backwards:
Copy Code code as follows:

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

3.2.9 sort
The sort method is used to sort the list at the original location, meaning to change the original list instead of simply returning a sorted copy of the list.
If you want to get a sort without changing the original value, you need to assign a value before you sort it:
Copy Code code as follows:

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

Note: In the example above, the assignment uses y=x[:], and fragmentation is a very efficient way to replicate the entire list. If you simply assign x to Y there is no (y=x), because doing so lets X and Y point to the same list.
Another way to get a sorted list copy is to use the sorted function:
Copy Code code as follows:

>>> 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 Sorting
If you want the elements to be sorted in a specific way, you can customize the comparison function in the form of compare (X,y). The built-in CMP function provides the default implementation of comparison functions:
Copy Code code as follows:

>>> 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 2 additional optional parameters-key and reverse. To use them, you must specify them by name.
Copy Code code as follows:

>>> 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. Tuple: Immutable sequence
The syntax for creating tuples is simple: if you separate some values with commas, you automatically create tuples.
Copy Code code as follows:

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

As the last example above, if you want to implement a tuple that includes a value, you must add a comma after the value.
4.1 Tuple function
Tuple takes a sequence as an argument and converts it to a tuple, and if the argument is a tuple, the argument is returned as is:
Copy Code code as follows:

>>> 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 are actually not complex, and there are not many other actions in addition to creating tuples and accessing tuple elements:
Copy Code code as follows:

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

A tuple is fragmented or a tuple, just like a list fragment or a list.

4.3 So, what's the point?
Tuples are irreplaceable:
(1) The tuple can be used as a key in the map, and the list is not.
(2) tuples exist as the return values of many built-in functions and methods.

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.