Python Handy notes the first (2) list and tuples

Source: Internet
Author: User
In Python, lists and tuples are data structures: sequences, each element in the sequence is assigned an ordinal, the position of the element, the position of the first element is 0, and so on. Sequence is the most basic data structure, lists and tuples have a certain difference between them, that is, the list can be modified, and tuples cannot be modified! If you want to add an element, it is best to use a list.

1, in Python , the most basic data structure is a sequence, each element of a sequence is assigned an ordinal, that is, the position of the element, called the index. The index starts at 0, 1 represents the penultimate element, and 2 represents the second-to-last element, so it can be accessed either from the beginning to the back, or from the back-to-front element.

2. There are 6 built-in sequences in the Python Order column: list, tuple, string, Unicode string, buffer object, Xrange object. There are two common types: lists and tuples.

The main difference between a list and a tuple is that the list can be modified and tuples cannot. In general, in almost all cases the list can be substituted for tuples. One exception: Use tuples as keys to dictionaries. The list cannot be used because the key cannot be modified.

3 . Each element in the list is separated by commas and written in square brackets.

4, the sequence can also contain other sequences.

5. General sequence operations: Index, Shard, add, multiply, check whether an element belongs to a member of a sequence, calculate the length of a sequence, find the largest element, find the smallest element.

6. Index:

All elements in the sequence are numbered, incremented from 0, and accessed separately by number.

You can also backtrack from the last element, where the last element is-1.

String literals can also use the index directly, without requiring a variable to refer to them, both of which are equally effective.

If a function call returns a sequence, it is possible to index the returned result directly.

7. Shard:

Use an index to access a single element in a sequence,

With shards, you can access multiple elements within a certain range.

The Shard operation needs to provide two indexes as a boundary, the element of the 1th index is contained within the Shard, and the 2nd index is not contained within the Shard.

How do I access the last element?

Only 9 elements in the original sequence, indexed from 0 to 8

Cannot get last element using Number[6:8]

Using the reciprocal method number[-3:-1] Also cannot get the last element

There are two ways to do this:

① to set the next boundary index out of range, such as Number[6:9], will cover the 8th element

② directly omits a trailing boundary index, such as number[6:], meaning that it can be read from the 6th to the last

Similarly, there are:

Two boundary indexes are empty, you can read all the elements.

Also, for number[-3:0], the result of an empty list appears because the previous boundary index element must be to the left of the next index element, otherwise the result is empty.

8. Set the step size for the Shard

A shard actually contains three parameters [boundary 1: Boundary 2: Step]

When you omit the step parameter, the step takes the default value of 1.

A step of 1 will facilitate all elements within the boundary.

The step is greater than 1 o'clock and the element is taken out of the interval.

For example, if you set the step size to 2, the first element is taken out of every 2 elements, or 1 elements are removed every 1 elements.

The step size cannot be 0, but the step can be negative, so that it is inverted, from right to left, and the corresponding boundary index is no longer the requirement for the first index element to the left of the 2nd index, but instead: the first index element needs to be on the right side of the second index element.

Like what:

Summarized as follows:

① step parameters can be omitted, omitted after the default value of 1;

② step is positive, from the left side of the sequence to the right, the result is this order, the step is negative, from the right side of the sequence to the left, the result is in this backward order (relative to the original sequence) arrangement;

③ step is positive, requires that the first index element must be on the left side of the second index element, and that the first index element must be on the right side of the second index element when the step is negative;

④ whether the step is positive or the step is negative, the first index element is removed and the second index element is not fetched.

9. Add the sequence:

Two sequences of the same type can be added.

Like what:

The string is added to the string, and the list is added to the list. The string cannot be added to the list.

10. Sequence multiplication:

Multiplying the number x by a sequence produces a new sequence of the same type, and the sequence of the new sequence is repeated x times.

If you want to initialize an empty sequence of 10 elements, you can use multiplication to do it, and here you will use a python built-in value of none.

None means nothing at all.

Remember that Python is case-sensitive.

11. Check for member presence:

Checks whether an element exists with a sequence, using in. Returns true if it exists, or false if it does not exist.

Above two examples, one can be used as a permission check, one can be used as a user list check.

Write a user name password check below:

12, the length, the minimum, the maximum value:

Use the Python built-in function Len (), Max (), Min () to find the length, maximum, and minimum values of the sequence. Such as:

13. List

A list can use all the standard actions that apply to a sequence, such as: Index, Shard, add, multiply, and so on.

List differences are characterized by sequences of other types, such as strings, tuples, and so on: Lists can be modified.

Therefore, the list has some special actions: negative elements, element deletions, shard assignments, and List methods.

(1) List () function:

The list () function applies to all types of sequences, not just strings.

(2) List assignment:

List assignment, you cannot assign a value to an element that does not exist in a location.

(3) Deleting an element

Remove the element from the list and use the DEL statement to implement it.

(4) Shard Assignment

The above example uses the list function to assign values to the Name[7:] This shard, changing the values of multiple elements in the list name at once.

The ① shard assignment can also complete the operation of replacing elements.

The example above is to substitute a long list for a medium-long element of the meta-list, but a direct substitution occurs when the substitution list is not replaced by a number of elements. As here, you use ' world ' and ' 123 ' to override the name list.

The ② shard assignment can also be done to insert an element.

When there are no substituted shard elements, the assignment becomes the directly inserted element.

③ Shard Assignment can also be done to delete an element.

Assigning a shard with an empty list is equivalent to deleting all the elements in that Shard directly.

This statement acts like Del Number[2:7].

(5) List method: Append

The Append method is used to append a new object to the end of the list.

Format: Object. Append (Parameter)

There can be only one parameter, which is the element to append to the object.

(6) List method: Count

The Count method is used to count the number of occurrences of an element in a list

(7) List method: Extend

The Extend method is primarily used to extend another list with one list.

Add the List2 extension directly to the end of the List1.

The extend extension operation differs from the connection operation in that the extended operation modifies the existing list, and the join operation returns a completely new list.

The JOIN operation using addition does not change the original list.

(8) List method: Index

The index method is primarily used to find the index position of the first occurrence of a value from a list.

Index will search for the first ' AAA ' position in the list and return its index value.

If there is no search, in other words, the object is not present in the list, then a long error will occur, resulting in an exception.

(9) List method: Insert

The Insert method is used to insert an object into the list.

(10) List method: Pop

The Pop method is used to remove an element from the list and return the value of the element.

By default, the last element is removed.

If you do not specify a parameter value in a pop (parameter), the last one is automatically removed, and if the parameter value is specified, the specified element is removed.

The Pop method returns the element to remove and completes the removal from the list.

The pop is equivalent to the stack of the stack, append equivalent to the stack in the stack.

Pop (0) can be implemented in FIFO in the queue.

(11) List method: Remove

The Remove method is used to remove the first occurrence of a value in the list.

Only the first occurrence is removed. There is no return value, which is the difference from pop, and when the remove item does not exist with the list, the list itself is not changed and an error is encountered.

(12) List method: Reverse

The reverse method stores the elements in the list in reverse.

If you only want to reverse the output of the list and not change the list itself, you can use the reversed () function to complete

(13) List method: Sort

Sort the list and change the list itself.

Letters and numbers are mixed together and are sorted according to ASCII code.

If you want to sort the list, but do not change the list itself. Then there are:

The X.sort () result is assigned to Y by assignment, but y is returned as null. It is not possible to describe this assignment because the sort method does not return any values.

If you first assign x by assigning a value to Y and then the sort () method for y, you want to sort Y by this method without affecting the x itself. But from the result, the sort of y still affects the X. The reason for this is that by y=x this type of assignment, it does not actually produce a new list to assign to Y, but just let y point to the same list as x, where x and y all point to the same list. Then the sort of y, which is essentially the same list that the X points to, also changes the X.

This allows x to produce a copy, sorting the copy without affecting the x itself is correct, but the assignment is not in the wrong form.

A shard operation allows you to quickly copy a list to another variable in its entirety.

Another way to get a sorted list copy without affecting the list itself is to use the sorted function.

Sorted () is a function, not a method. Therefore cannot be used like x.sotred ().

The sorted () function can be applied to any sequence.

The sort method is sorted by default in ascending order. If you need to customize the direction of the sort, you can use the built-in function CMP () to implement.

The CMP (x, y) function is used to compare 2 objects if x y returns 1.

The Sort method also has two additional optional parameters, key and reverse.

14, meta-group:

Tuples and lists are the same sequence, and the only difference is that tuples cannot be modified.

Lists are enclosed in square brackets, while tuples are enclosed in parentheses.

Empty list is [], empty tuple is ()

Tuple of an element (1,)-----also need a comma, the comma is very important

Tuple of multiple elements (1,2,3,4)

If an element is written as (1), then in fact it is not a tuple, is the number 1

(1) Tuple function

List () functions similar to lists

When you use the tuple function, you can split the string and list into tuples.

(2) Creating tuples

Use the tuple () function to create

Enumeration creation

(3) Accessing tuples and tuple shards

Tuples are also tuples after they are fragmented.

(4) In general, you can use lists instead of tuples when you do not change the content itself.

However, in two cases, tuples are irreplaceable.

① tuples can be used as keys in mappings, but not in lists.

The ② tuple exists as a return value for many of the built-in functions and methods.

15, Summary:

Sequence: A data structure in which the elements are numbered starting with 0 and numbered-1 as the first element in the countdown.

A typical sequence is a list, a string, a tuple. The list can be modified, and strings and tuples cannot be modified, and once created, they are fixed.

A single element or multiple elements of a sequence can be accessed through a shard operation. The Shard needs to specify the starting and ending positions. The starting position element is contained within the Shard, and the terminating position element is not contained within the Shard.

  • 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.