Python list, tuple, dictionary

Source: Internet
Author: User
Tags python list

    1. One of the data types built into Python is the list: lists. List is an ordered collection that can be added and deleted at any time.

The element.


>>>classmates = [' Michael ', ' Bob ', ' Tracy ']

>>>classmates


Use the Len () function to get the number of list elements:

>>>len (Classmates)

Use an index to access the elements of each location in the list, remembering that the index starts at 0:

The list is a mutable, ordered table, so you can append the element to the end of the list, using the Append function

>>>classmates.append (' Adam ')

>>>classmates

You can also insert elements into the specified position, such as the index number 1, using the Insert function:

>>>classmates.insert (1, ' Jack ')

>>>classmates

To delete the element at the end of the list, use the Pop () method:

>>>classmates.pop ()

>>>classmates

To delete an element at a specified location, use the pop (i) method, where I is the index position, or you can remove it using the Remove () method:

>>>classmates.pop (1)

>>>classmates

>>>classmates.remove (' Bob ')

>>>classmates

To replace an element with another element, you can assign a value directly to the corresponding index position:

>>>classmates[1]= ' Sarah '

>>>classmates

To sort the elements of a list, you can use the sort () method, which can be reversed using the reverse () method:

>>>classmates.sort ()

>>>classmates

>>>classmates.reverse ()

>>>classmates

The data type of the elements in the list can also be different, and the list element can be another list

>>>classmates = [' Michael ', ' Bob ', [' asp ', ' php '], ' Tracy ']

>>>classmates

The elements in the list are like queues, and we can use the slicing method to access any part of them. [Start:stop:step] that is [start index: End index: Step value], Note: The step value cannot be 0.


2. Another ordered list is called a tuple: a tuple. Tuple and list are very similar, but a tuple cannot be modified once initialized

Use parentheses () to represent a tuple.

The so-called "invariant" of a tuple is that each element of a tuple refers to the constant . That point ' a ', it cannot be changed to point to ' B ', pointing to a list, cannot be changed to point to other objects, but the list itself is variable! To create a tuple that does not change content, you must ensure that each element of the tuple itself cannot be changed. List and tuple are Python's built-in ordered set, one variable, one immutable. Choose to use them as needed.

The two commonly used methods of a tuple are: count () counts the number of elements of a tuple and index () returns the subscript of an element.

Note: When a single tuple element is added ', ' after the element, the Python interpreter is not recognized as a tuple type.


3. Python built-in dictionary: dict support, Dict full name dictionary, also known as map in other languages, using key-value (Key-value) storage, with extremely fast lookup speed. A dictionary consists of a pair of keys and corresponding values. Dictionaries are also referred to as associative arrays or hash tables.

Creation of dictionaries:

    • Create a dictionary directly

>>>d={' One ': 1, ' both ': 2, ' Three ': 3}

>>>print D

    • Create a dictionary from Dict or create a dictionary from a keyword

>>>items=[(' One ', 1), (' One ', 2), (' Three ', 3), (' Four ', 4)]

Content in >>>print u ' items: '

>>>print Items

>>>print u ' uses dict to create dictionaries, Output dictionary contents: '

>>>d=dict (items)

>>>print D

Attention:
Each key and value is separated by a colon (:), each pair is comma-delimited, each pair is separated by commas, and the whole is placed in curly braces ({}).
The key must be unique, but the value does not have to be.
The value can take any data type, but it must be immutable, such as a string, number, or tuple.

Method of the Dictionary:

  1. Clear function: Clears all items in the dictionary

  2. copy function: Returns a new dictionary with the same key value

  3. Fromkeys function: Use the given key to create a new dictionary, the default corresponding value of the key is non

  4. Get function: Access dictionary member, get function can access the dictionary does not exist in the key, when the key does not exist is return none

  5. Has_key function: Check if the dictionary contains the given key

  6. Items and Iteritems functions: Items return all dictionary items as a list, items from the list (key, value), iteritems similar to items, but return an iterator object instead of a list

  7. Keys and Iterkeys:keys return the keys in the dictionary as a list, Iterkeys the iterator that returns the key

  8. Pop function: Delete the corresponding key in the dictionary

  9. Popitem function: Move out of an item in the dictionary

  10. SetDefault function: Similar to the Get method, gets the value associated with the given key, or sets the corresponding key value if the dictionary does not contain the given key

  11. Update function: Updating another dictionary with one dictionary

  12. Values and Itervalues functions: Values return a value in the dictionary as a list, Itervalues returns a worthwhile iterator, because the values in the dictionary are not unique, so the list can contain duplicate elements

The method of putting data into dict, in addition to the initialization of the specified, can also be placed through the key: Because a key can only correspond to a value, so, multiple times a key into value, the following value will be the previous value is flushed out: 1. To avoid the key does not exist error, there are two ways, One is to determine whether a key exists by in: 2. The Get method provided by Dict, if key does not exist, can return None, or the value specified by itself:

Note: The order of dict internal storage is not related to the order in which key is placed.

Compared with list, Dict has the following features:

1. Find and insert the speed is very fast, will not increase with the key increase;

2. It takes a lot of memory and a lot of wasted memory.

And the list is the opposite:

1. The time to find and insert increases as the element increases;

2. Small footprint, very little wasted memory.

So, Dict is a way of exchanging space for time.

Dict can be used in many places where high-speed lookups are needed, almost everywhere in Python code, it is important to use dict correctly, and the first thing to keep in mind is that the Dict key must be an immutable object.

This is because Dict calculates the storage location of value based on key, and if each calculation of the same key results in a different result, the dict interior is completely chaotic. The algorithm for calculating the position by key is called the hash Algorithm (hash).

To ensure the correctness of the hash, the object as a key can not be changed. In Python, strings, integers, and so on are immutable, so you can safely use them as keys. The list is mutable and cannot be similar to Key:set and dict, but it is also a set of keys, but does not store value. Because key cannot be duplicated, there is no duplicate key in set.

The only difference between set and dict is that it does not store the corresponding value, but the set principle is the same as the dict, so it is also not possible to put mutable objects, because it is not possible to determine whether the two Mutable objects are equal, and there is no guarantee that there will be no duplicate elements inside the set.


This article is from the "brave Heart Zhao Xiao Bai" blog, please make sure to keep this source http://3024783.blog.51cto.com/3014783/1975429

Python list, tuple, dictionary

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.