The difference and usage of the built-in data type List,tuple,dict,set in Python

Source: Internet
Author: User
The Python language is simple and straightforward, and can be used with less code to achieve the same functionality. This is where Python's four built-in data types work, they are list, tuple, Dict, set. Here is a concise summary of them.

List

The literal meaning is a collection, in Python the elements in the list are denoted by brackets [], and you can define a list like this:

L = [n, ' China ', 19.998]

You can see that the types of elements are not required to be the same. Of course, you can also define an empty list:

L = []

The list in Python is ordered, so it's obvious that you want to access the list by ordinal, like an array subscript, which starts with the subscript 0:

>>> Print l[0]12

Don't cross the border, or you will get an error

>>> Print L[3]traceback (most recent call last): File "
 
  
   
  ", line 1, in 
  
   
    
   indexerror:list Index
  
   
 
   out of range

The list can also be accessed in reverse order, using the subscript "bottom X" to denote a sequence number, such as 1, which represents the penultimate element:

>>> L = [n, ' China ', 19.998]>>> print l[-1]19.998

4 of the words, apparently crossed the border.

>>> Print L[-4]traceback (most recent call last): File "
 
  
   
  ", line 1, in 
  
   
    
     print L[-4]index Error:list index
  
   
 
   out of range>>>

The list is added to the trailer via the built-in append () method, which is added to the specified position by the Insert () method (subscript starting from 0):

>>> L = [n, ' China ', 19.998]>>> l.append (' Jack ') >>> print l[12, ' China ', 19.998, ' Jack ']>& Gt;> L.insert (1, 3.14) >>> print l[12, 3.14, ' China ', 19.998, ' Jack ']>>>

Delete the last trailing element via pop (), or specify a parameter to delete the specified position:

>>> l.pop () ' Jack ' >>> print l[12, 3.14, ' China ', 19.998]>>> l.pop (0) 12>>> print l[ 3.14, ' China ', 19.998]

You can also use the subscript to copy and replace

>>> l[1] = ' America ' >>> print l[3.14, ' America ', 19.998]

Tuple

A tuple can be seen as a "constant" list, and access is also indicated by the subscript, with parentheses ():

>>> t = (3.14, ' China ', ' Jason ') >>> print t (3.14, ' China ', ' Jason ')

However, the substitution cannot be re-assigned:

>>> t[1] = ' America ' Traceback (most recent call last): File "
 
  
   
  ", line 1, in 
  
   
    
     t[1] = ' Ame Rica ' TypeError: ' Tuple ' object does
  
    not a support item assignment
 
  

There are no pop and insert, append methods.

You can create a tuple of empty elements:

t = ()
or element tuple (such as adding a comma to prevent and declare a shape ambiguity):

T = (3.14,)

So what is the use of this type of tuple? You know, if you want a function to return multiple return values, you can simply return a tuple, because the tuple contains multiple values, and is immutable (like Final in Java). Of course, a tuple is also mutable, such as:

>>> t = (3.14, ' China ', ' Jason ', [' A ', ' B ']) >>> print t (3.14, ' China ', ' Jason ', [' A ', ' B ']) >>> L = t[3]>>> L[0] = 122>>> l[1] = 233>>> print t (3.14, ' China ', ' Jason ', [122, 233])

This is because tuple so-called immutable refers to the position of the point is immutable, because the fourth element in this example is not a basic type, but a list type, so T points to the position of the list is constant, but the contents of the list itself can be changed, Because the list itself is not contiguous in memory allocations.

Dict

Dict is a very important data type in Python, as it literally means, it is a dictionary, actually key-value key-value pairs, similar to HashMap, you can use curly braces {} to define a struct like a C language:

>>> d = {  ' Adam ': 75}>>>, ' Lisa ': $, ' Bart ': ', ' Paul ': ' Lisa ': ' Paul ' on the  print d{' : "Adam": Up, ' Bart ': 59}

You can see that the printed results are in key:value format, and the Len function can be used to calculate its length (List,tuple can also):

>>> Len (d)
4

You can add elements in dict directly by key-value pairs:

List and tuple use subscript to access content, while Dict uses key to visit: (String, Integer, float, and tuple tuple can be used as dict key)

>>> print d[' Adam ']95

If key does not exist, it will error:

>>> print d[' Jack ']traceback (most recent): File "
 
  
   
  ", line 1, in 
  
   
    
     print d[' Jac K ']keyerror: ' Jack '
  
   
 
  

So it's a good idea to check if the key exists before accessing it:

>>> if ' Adam ' in d:print ' exist key ' exist key

or directly with the Get method of insurance:

>>> print d.get (' Adam ') 95>>> print d.get (' Jason ') None

As for traversing a dict, it is actually traversing all of its key sets, and then using this key to get the corresponding value:

>>> for key in D:print key, ': ', D.get (key) lisa:85paul:75adam:95bart:59

Dict has some features:

Find Fast. Either 10 or 100,000, the speed is the same, but the cost is large memory. List, in contrast, consumes less memory, but looks slow. This is like the difference between an array and a linked list, the array does not know how much space to open up, so often start to open up a large space, but directly through the subscript lookup speed, but the list of small space, but the time of the search must be sequential traversal caused by slow speed
No order. Dict are not sequential, and list is an ordered set, so you cannot use Dict to store an ordered set
Key is immutable and value is variable. Once a key value pair is added to the dict, its corresponding key cannot be changed, but value can be changed. So list can not be considered as Dict key, but can be used as value:

>>> print d{' Lisa ': $, ' Paul ': ' Adam ': Jone, ' ' Bart ': ' 59}>>> d[' newlist ', ' Jack ' ']>>> print d{' Bart ':, ' newlist ': [[75], ' Jack '], ' Adam ': ' The ' Jone ': "The", ' Lisa ': ' Paul ':}

Key cannot be duplicated. (The following example adds a ' Jone ': 0, but in fact already has the ' jone ' this key, so just changed the original value)

>>> print d{' Bart ': ' NewList ': [a ', ', ' Jack '], ' Adam ': The ' Jone ': "The ' Lisa ': ' Paul ': 75}>>> d[' jone ' = 0>>> print d{' Bart ':, ' newlist ': [0, ' + ', ' Jack '], ' Adam ': ' The ' Jone ': 75 ', ' Lisa ': +, ' Paul ': +-------'

Dict merge, how to combine two dict into one, you can use the Dict function:

>>> D1 = {' Mike ':, ' jack ':19}>>> d2 = {' Jone ': $, ' ivy ':17}>>> dmerge = Dict (D1.items () + D2. Items ()) >>> print dmerge{' Mike ': ' Jack ': +, ' jone ': +, ' Ivy ': 17}

Or

>>> dMerge2 = dict (d1, **d2) >>> print dmerge2{' Mike ': ' Jack ': +, ' jone ': +, ' Ivy ': 17}

Method 2 is much faster than Method 1, and Method 2 is equivalent to:

>>> dMerge3 = dict (d1) >>> dmerge3.update (D2) >>> print dmerge{' Mike ':, ' Jack ': +, ' Jone ': 2 2, ' Ivy ': 17}

Set

Set is like pulling the key out of the dict, similar to a list, but the content cannot be duplicated and created by calling the set () method:

>>> s = set ([' A ', ' B ', ' C ')
Just as the dict is unordered, set is unordered and cannot contain duplicate elements.

The meaning of accessing a set is simply to see if an element is in the set:

>>> print ' A ' in strue>>> print ' D ' in Sfalse

The case is sensitive.

Also traverse through for:

s = set ([' Adam ', ' + '), (' Lisa ', ' ($), (' Bart ', ')]) #tuplefor x  in S: Print x[0], ': ', x[1]>>>lisa:85adam:95 bart:59

Add and remove elements by adding and removing (keep not repeating), adding elements, using the set's Add () method:

>>> s = Set ([1, 2, 3]) >>> S.add (4) >>> print Sset ([1, 2, 3, 4])

If the added element already exists in set, add () will not error, but will not be added:

>>> s = Set ([1, 2, 3]) >>> S.add (3) >>> print sset ([1, 2, 3])

When removing elements from a set, use the Remove () method of Set:

>>> s = Set ([1, 2, 3, 4]) >>> S.remove (4) >>> print Sset ([1, 2, 3])

If the deleted element does not exist in the set, remove () will error:

>>> s = Set ([1, 2, 3]) >>> S.remove (4) Traceback (most recent): File "
 
  
   
  ", line 1, I n
 
   
    
   keyerror:4
  
    
  

So if we want to determine if an element fits within some different conditions, using set is the best option, the following example:

months = set ([' Jan ', ' Feb ', ' Mar ', ' Apr ', ' may ', ' June ', ' Jul ', ' April ', ' Sep ', ' Oct ', ' Nov ', ' Dec ',]) x1 = ' Feb ' x2 = ' Sun ' if X1 in Months:  print ' X1:ok ' else: print '  x1:error ' if x2 in months:  print ' X2:ok ' else:  print ' X2:error ' >&G T;>x1:okx2:error
  • 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.