Simple learning notes for lists, dictionaries, and tuples in Python, and python learning notes

Source: Internet
Author: User
Tags python list

Simple learning notes for lists, dictionaries, and tuples in Python, and python learning notes

List

List is the most flexible ordered collection object type in Python. Different from a string, a list can contain any type of objects: Numbers, strings, or even other lists. A list is a mutable object that supports in-situ modification.

The Python list is:

  • Ordered Set of any object
  • Read through offset
  • Variable Length, heterogeneous, and arbitrary nesting
  • Classification of Variable Sequences
  • Object reference array (the list stores object references rather than object copies)

List in actual application

> Basic list operations
Because the list is a sequence, it supports many operations that are the same as strings. The response of the "+" and "*" operations in the list is similar to the string. The two operations mean merging and repeating, but a new list, not a string.

> Index, partition, and Matrix
For the list, the index and sharding operations are basically the same as those in the string. However, the index result of the list is the object at the specified offset (no matter what type), and a new list is often returned for list sharding.

matrix = [[1,2,3],[4,5,6],[7,8,9]]

The above Code defines a 3*3 two-dimensional matrix.

> Original modification list
Assignment of indexes and shards

When using the list, you can assign a value to a specific item (offset) or the entire part (fragment) to change its content. The assignment of the index and fragment is both in-situ modification, they modify the list directly, instead of generating a new list as a result. the Index Assignment in Python is very similar to that in C and most other languages -- Python replaces the specified offset object reference with a new value.

Call List Method

The most common list method is append, which can simply add a single item (Object Reference) to the end of the list. Different from merging, append allows a single object instead of a list. The results of L. append (X) and L + [X] are similar. The difference is that the former modifies L in situ, while the latter generates a new list. Another common method is sort, which sorts the list in the same place. Sort uses the comparison test of the Python standard as the default value (here it refers to the string comparison) and sorts it in ascending order. In addition, we can pass in a keyword parameter to modify the sorting behavior-this is a special "name = value" language in the function call that is passed by name.

Note that append and sort modify the list object in the same place, and the returned results of the method do not return the list (technically, both return values are None ). If you write a statement similar to L = L. append (X), the modified value will not be obtained (in fact, the reference of the entire list will be lost ).

  • Reverse: In-situ reverse list
  • Extend: insert multiple elements at the end
  • Pop: Delete the last element and return the deleted Value.
  • Remove: deletes an element by using a value.
  • Insert: insert an element at the offset.
  • Index: returns the offset of an element.

Dictionary

If you think of the list as an ordered object set, you can regard the dictionary as an unordered set. The main difference is that the element in the dictionary is accessed by a key, instead of using offset access. The main attributes of the Python dictionary are as follows:

  • Reads data by key instead of offset.
  • Unordered set of any object
  • Variable Length, heterogeneous, arbitrary nesting
  • Variable ing type
  • Object Reference Table (hash) (the dictionary stores object references rather than object copies)
  • Dictionary in practical application

> Original dictionary Modification
Same as the list, assigning a value to an existing index in the dictionary changes the value associated with the index. However, unlike the list, a new element is generated in the dictionary whenever a value is assigned to the new dictionary key (the key that was not previously assigned.

> Other dictionary Methods

  • Keys: returns the dictionary key list.
  • Values: returns a list of dictionary values.
  • Items: returns the key, value pair of the dictionary.
  • Update: Merge
  • Pop: deletes a key from the dictionary and returns its value.

> Dictionary usage considerations

  • The sequence operation is invalid.
  • Assign a value to the new index to add an item.
  • The key is not always a string.

> Other methods for creating dictionaries

#Method1D = {'name':'mel','age':45}#Method2D = {}D['name']='mel'D['age']=45#Method3D = dict(name='mel',age=45)#Method4D = dict([('name','mel'),('age',45)])

The above four forms create the same dictionary.

> Dictionary changes in Python3.0
The dictionary function has changed in Python3.0. Specifically, the dictionary in Python3.0:

  • Supports a new dictionary parsing expression, which is a close relative of list and set parsing"
  • For the D. key, D. values, and D. items methods, an iterative view is returned, instead of a list.
  • Because of the previous point, the new encoding method needs to be traversed by the sort key.
  • Comparison of relative sizes is not directly supported. Instead, manual comparison is supported.
  • The D. has_key method is no longer available. Instead, use the in member relationship test.

Dictionary View

In Python3.0, the dictionary keys, values, and items all return view objects. In Python2.6, they return the actual result list. The dictionary views in Python3.0 cannot be changed after they are created. They can dynamically reflect the changes made to the dictionary after the view objects are created:

D={'a':1,'b':2,'c':3}K = D.keys()V = D.values()del D['b']list(K)

In the above Code, the result of the last line is ['A', 'C'].

The objects returned by the keys method are similar to the set and common operations such as intersection and union are supported. The values view is not like this because they are not unique. But the items result is, if (key, value) the pair is unique and can be hashed.

Tuples

Tuples are composed of Simple objects. Tuples are very similar to lists, except that tuples cannot be modified in their original fields (they are immutable). They are generally written as a series of items in parentheses (rather than square brackets. Its attributes include:

  • Ordered Set of any object
  • Access through offset
  • It belongs to an unchangeable sequence type
  • Fixed Length, heterogeneous, arbitrary nesting
  • Array referenced by the object

> Tuples in actual applications

Special Syntax of tuples: comma and parentheses

Since parentheses can also enclose expressions, if a single object in parentheses is a group object instead of a simple expression, Python needs to be particularly described. If you really want to get a tuple, you only need to add a comma after this single element and before closing the parentheses.

x = (40)y = (40,)

In the above Code, the x in the first line is an integer, And the y in the second line is a tuple containing an element 40.

Conversion, method, and immutability

The operation of tuples is the same as that of strings and lists. The difference is that "+", "*", and the multipart operation will return the new element group when applied to tuples, the tuples do not provide methods in strings, lists, and dictionaries.

> Why does the list contain tuples?
The immutability of tuples provides some integrity, so that you can ensure that the tuples are not referenced and modified by another in the program, and the list does not have such a guarantee.

Articles you may be interested in:
  • An example is provided to illustrate the usage of the list Data Structure in Python.
  • How to convert a list into a dictionary data structure using Python
  • Python has three built-in data structures: List, tuples, and dictionary.
  • List, Dictionary, tuples, and collection Data Structure in Python
  • How to convert a class object to a json/dictionary in python
  • Python sorts dictionaries by value
  • A brief summary of the similarities and differences between sequences and dictionaries in Python
  • A Preliminary Exploration of the dictionary and member operators in Python
  • In-depth analysis of list and its slicing and iteration operations in Python

Related Article

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.