Summary of common data types in Python

Source: Internet
Author: User

Python provides a variety of data types to hold data item collections, mainly including sequences (list and tuple tuple), mappings (such as dictionary dict), collections (set), which are described in one of these ways:

A sequence

1. List of lists

A list is an ordered collection of elements that are variable in relation to tuples and strings, and can be added and removed at any time.

(1) Create List

Test on the command line as follows:

>>> L1 = [a]>>>l1[1, 2, 3]>>> L2 = ['ABC']>>>l2['ABC']>>> L3 = ["a","b","C"]>>>l3['a','b','C']

Note that the string must be quoted.

It is very useful to create a list of strings through the list, such as:

 >>> L = list ( python   " "  >>> l[  '       n   ' ] 

(2) Visit list

Depending on the index, note that you cannot cross the line, which is particularly similar to arrays:

>>> l[0]'P'>>> l[-1]'n' 

(3) Adding new elements

Append the new element to the end of the list using the Append () method, and insert () to add a new element to a specific location.

(4) Deleting an element

The delete element can take the pop () method, execute L.pop () to delete the last element of the list, if it is a specific position can take the pop (2), 2 represents the position.

(5) Replacement

The substitution is simple, and the direct index is fine.

(6) Printing

>>> L = ['a','b','c'  ] for in L:    print(i)   ABC

2. Tuple

(1) Create

Unlike list, a tuple is generally used (), and is tested in the command line as follows:

t= 1,2,3>>> T (1, 2, 3)>>> t = (All-in-all)>>> T (1, 2, 3) 
    "ABC">>> T'abc'

Create empty tuple: T = ()

Defines a tuple of an element:

>>> t = (1)>>> T1

This runs the result is right, it seems correct, but this definition is not true, this definition is not tupel, but 1 this number, this is because the parentheses () can represent both a tuple and a mathematical formula in parentheses, which creates ambiguity, so Python rules, in this case , calculated by parentheses, the result is naturally 1. Therefore, you must add a comma when defining a tuple with one element, as follows:

>>> t = (1,)>>> T (1,)

(2) Access

The direct index is good, as follows:

>>> T = ($)>>> t[1]2

(3) Change

The tuple defined above is immutable, but we can define a list in a tuple to modify it:

 >>> T = (1,2,[ " a  , "  b    ')  >>> t[2][0]   '   c   '  >>>]) 

In a tuple, although the element cannot be modified, we can concatenate it together:

>>> = [T1]>>> T2 = [4,5,6]>>> T3 = T1 + T2>>> t3[ 1, 2, 3, 4, 5, 6]

3. String

(1) Create

" Hello Python ">>> str'Hello Python'

(2) Access

>>> str[0]'H'

(3) Add

"""Python">>> str3 = str1 + str2> >> str3'Hello Python'

4. General-Purpose sequence operation method

(1) Index

In the access sequence element, as follows:

>>> L = ['a','b','C']>>> l[1]'b'>>> T = (A)>>>T[0]1>>> str ="Python">>> str[4]'o'

(2) sharding

Shards are used to access elements of a certain range, and shards are usually implemented by two indexes separated by colons, and are commonly seen in the following ways:

>>> A = List (range)>>>1, 2, 3, 4, 5, 6, 7, 8, 9]>>> b = a[1:5
   
    ]>>>
     b[1, 2, 3, 4
    ]>>> c = a[-3:-1
    ]>>>
     c[7, 8
    ]< /c8>>>> d = a[1:10:2]>>> d[1, 3, 5, 7, 9]
   

Two Mappings (dictionary)

Each element in the map has a professional name, called the key. The dictionary is the only built-in mapping type in Python, which we'll cover in more detail:

(1) Key type

A dictionary (dict) is a container that stores unordered key-value mappings (key/value) of type data that can be a key of a

Word, string, or tuple, the key must be unique. In Python, numbers, strings, and tuples are designed to be immutable types, and common lists and collections (sets) are mutable, so lists and collections cannot be keys to the dictionary. The key can be any immutable type, which is the most powerful dictionary in Python.

(2) Create

>>> d = {}>>> d[1] = 1>>> d{1:1}>>> d['cat  'Lucy'>>> d{'cat' ' Lucy '}

(3) Find

Dict is to find value by key, which represents the relationship of meaning, which can be accessed by D[key] Dict:

>>> d['cat']'Lucy'

(4) Traverse

>>> d = {}>>> d['cat'Lucy'> >> d['dog'Ben' for in d:     Print " : ", D[key])

Results

Cat:lucy

Dog:ben

(5) Advantages and disadvantages

The first feature of Dict is that the search speed is fast, and the speed of the search is independent of the number of elements, while the search speed of the list decreases with the increment of the element, and the second characteristic is that the stored key-value order pairs are not sequential; The third feature is that the element is immutable as a key, So list cannot be a key.

The disadvantage of dict is that it takes up a lot of memory, and it wastes a great deal of content.

Three sets (set)

Dict is the establishment of a series of mapping relationships, and set is to create a series of unordered, non-repeating elements.

(1) Create

The way to create a set is to call set () and pass in a list,list element as the set element.

>>> S = set ([s{])>>> 1, 2, 3}

Repeating elements are automatically filtered in set, such as:

>>> S = set ([1,1,2,3,4,5,4])>>> s{1, 2, 3, 4, 5}

(2) Add

Add (), there are repeating elements can be added, but will not have effect:

>>> S.add (4)>>> s{1, 2, 3, 4, 5}>>> S.add (9)>> > s{1, 2, 3, 4, 5, 9}

(3) Delete

>>> S.remove (9)>>> s{1, 2, 3, 4, 5}

(4) intersection, and set

Set can be regarded as a set of unordered and non-repeating elements in mathematical sense, so two sets can do the intersection and set of mathematical meanings:

>>> S1 = set ([Up])>>> S2 = set ([2,3])>>> s1&s2{2} >>> s1| s2{1, 2, 3}

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 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 the set will "have no duplicate elements"

The main differences between the four list,tuple,dict and set

1. List

A list is a set of ordered elements enclosed in square brackets;

The list can be used as an array starting with the 0 subscript, and the first element of any non-empty list is always l[0], and the negative index starts counting forward from the end of the list to access the element. The last element of any non-empty list is always l[-1];

With the Shard function, two lists can be added;

Append appends a single element to the end of the list;

Insert inserts a single element into the list;

Extend is used to connect to the list, using a list parameter to call;

Append accepts a parameter, which can be any data type, and is simply appended to the tail of the list;

Index finds the first occurrence of a value in the list and returns the index value;

To test whether a value is inside a list, use in, if the value exists, it returns TRUE, otherwise it is returned to False;

Remove removes the first occurrence of a value from the list;

Pop can delete the last element of the list, and then return the value of the deleted element, using the index to delete the value of the set position;

2.tuple

A tuple is immutable list, and creating a tuple cannot change it in any way;

Defining a tuple is to enclose the entire set of elements in parentheses, which is an ordered set;

The index of a tuple is the same as list starting from 0, so the first element of a non-empty tuple is always t[0];

A negative index is counted as a list from the tail of a tuple;

As with list shards (slice) can also be used. When a tuple is split, a new tuple is obtained;

No append, Extend, remove or pop methods, and index methods;

You can use in to see if an element exists in a tuple.

3.dict

Dict defines a one by one correspondence between the key and the value, each of which is a key-value pair;

The entire element set is enclosed in curly braces, and an ordered set;

You can get value by key, but you can't get key through Vaule;

There can be no duplicate key in a dict, and key is case-sensitive;

Keys can be immutable types, such as numbers, strings, or tuples;

Use del key to delete the independent elements in the dict;

Clear clears all elements in the Dict.

4.set

Set is the establishment of a series of unordered, non-repeating elements;

The way to create a set is to call set () and pass in a list,list element as the set element;

The only difference between set and dict is that the corresponding value is not stored.

These are some of my own summary, but also hope that everyone's generous enlighten ~

Summary of common data types 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.