Differences and usage of built-in data types list, tuple, dict, and set in Python

Source: Internet
Author: User
This article mainly introduces the differences and usage of the built-in data types list, tuple, dict, and set in Python, which are all very basic knowledge and meticulous and comprehensive, if you have any need, refer. The Python language is concise and clear, and you can use less code to implement the same function. The four built-in data types of Python are indispensable. They are list, tuple, dict, and set. Here is a concise summary of them.

List

It is a set. In Python, the elements in the List are represented by brackets []. A List can be defined as follows:

L = [12, 'China', 19.998]

We can see that the element types are not required to be the same. Of course, you can also define an empty List:

L = []

In Python, the List is ordered. Therefore, to access the List, you must access the List by serial number, just like the subscript of the array. The subscript starts from 0:

>>> print L[0]12

Do not cross the border. Otherwise, an error will be reported.

>>> print L[3]Traceback (most recent call last): File "
 
  ", line 1, in 
  
   IndexError: list index out of range
  
 

List can also be accessed in reverse order. The subscript "x" is used to represent the sequence number. For example, the subscript-1 indicates the first element to be counted down:

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

-4 is clearly out of bounds.

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

List is added to the end by using the built-in append () method, and to the specified position by using the insert () method (subscript starts from 0 ):

>>> L = [12, 'China', 19.998]>>> L.append('Jack')>>> print L[12, 'China', 19.998, 'Jack']>>> L.insert(1, 3.14)>>> print L[12, 3.14, 'China', 19.998, 'Jack']>>>

You can use pop () to delete the last tail element. You can also 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 replace it by subscript.

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

Tuple

Tuple can be seen as a "unchanged" List. The access is also indicated by subscript, represented by parentheses:

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

However, you cannot replace the Value assignment:

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

There are no pop, insert, or append methods.

You can create a tuple for an empty element:

T = ()
Or single-element tuple (for example, adding a comma to prevent an integer ambiguity ):

T = (3.14 ,)

So what is the use of the tuple type? You need to know that if you want a function to return multiple return values, you only need to return one tuple, because tuple contains multiple values, and it is immutable (like final in java ). Tuple is also variable, for example:

>>> 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's so-called immutable refers to the immutable pointing position, because the fourth element in this example is not a basic type, but a List type, therefore, the position of the List pointed by t is unchanged, but the content of the List itself can be changed, because the allocation of the List itself in the memory is not continuous.

Dict

Dict is a very important data type in Python. Just like its literal meaning, it is a living dictionary, which is actually a Key-Value pair, similar to HashMap, you can use braces {} to define a struct similar to a C language:

>>> d = {  'Adam': 95,  'Lisa': 85,  'Bart': 59,  'Paul': 75}>>> print d{'Lisa': 85, 'Paul': 75, 'Adam': 95, 'Bart': 59}

We can see that all the printed results are in the Key: Value format. You can use the len function to calculate its length (List, tuple ):

>>> Len (d)
4

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

>>> print d{'Lisa': 85, 'Paul': 75, 'Adam': 95, 'Bart': 59}>>> d['Jone'] = 99>>> print d{'Lisa': 85, 'Paul': 75, 'Adam': 95, 'Jone': 99, 'Bart': 59} 

List and Tuple use subscript to access the content, while Dict uses Key to access the content: (string, integer, floating-point, and meta-group tuple can both be used as the key of dict)

>>> print d['Adam']95

If the Key does not exist, an error is returned:

>>> print d['Jack']Traceback (most recent call last): File "
 
  ", line 1, in 
  
     print d['Jack']KeyError: 'Jack'
  
 

Therefore, it is best to check whether the key exists before accessing:

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

Or directly use the insurance get method:

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

As for traversing a dict, it is actually traversing the set of all its keys, and then using this Key to obtain the corresponding Value:

>>> for key in d : print key, ':', d.get(key)Lisa : 85Paul : 75Adam : 95Bart : 59

Dict has some features:

Fast search speed. The speed is the same for both 10 and 0.1 million, but the cost is high memory consumption. On the contrary, the List occupies a small amount of memory, but the query speed is slow. This is like the difference between arrays and linked lists. arrays do not know how much space they need to open up, so they often start to open up a large space, but it is faster to search directly by subscript; the linked list occupies a small amount of space, but it must be retrieved sequentially, resulting in slow speed.
No order. Dict is ordered, while List is an ordered set. Therefore, you cannot use Dict to store Ordered Sets.
The Key is not variable, and the Value is variable. Once a key-Value pair is added to dict, the corresponding key cannot be changed, but the Value can be changed. Therefore, the List cannot be used as the Key of Dict, but can be used as the Value:

>>> print d{'Lisa': 85, 'Paul': 75, 'Adam': 95, 'Jone': 99, 'Bart': 59}>>> d['NewList'] = [12, 23, 'Jack']>>> print d{'Bart': 59, 'NewList': [12, 23, 'Jack'], 'Adam': 95, 'Jone': 99, 'Lisa': 85, 'Paul': 75}

The Key cannot be repeated. (In the following example, A 'jone': 0 is added, but actually the Key 'jone' already exists, so the original value is changed)

>>> print d{'Bart': 59, 'NewList': [12, 23, 'Jack'], 'Adam': 95, 'Jone': 99, 'Lisa': 85, 'Paul': 75}>>> d['Jone'] = 0>>> print d{'Bart': 59, 'NewList': [12, 23, 'Jack'], 'Adam': 95, 'Jone': 0, 'Lisa': 85, 'Paul': 75}

The Dict function can be used to merge two Dict into one:

>>> d1 = {'mike':12, 'jack':19}>>> d2 = {'jone':22, 'ivy':17}>>> dMerge = dict(d1.items() + d2.items())>>> print dMerge{'mike': 12, 'jack': 19, 'jone': 22, 'ivy': 17}

Or

>>> dMerge2 = dict(d1, **d2)>>> print dMerge2{'mike': 12, 'jack': 19, 'jone': 22, 'ivy': 17}

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

>>> dMerge3 = dict(d1)>>> dMerge3.update(d2)>>> print dMerge{'mike': 12, 'jack': 19, 'jone': 22, 'ivy': 17}

Set

Set is like extracting the key from Dict. It is similar to a List, but the content cannot be repeated. It is created by calling the set () method:

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

To access a set, you only need to check whether an element is in the set:

>>> print 'A' in sTrue>>> print 'D' in sFalse

It is case sensitive.

You can also traverse through:

s = set([('Adam', 95), ('Lisa', 85), ('Bart', 59)])#tuplefor x in s:  print x[0],':',x[1]>>>Lisa : 85Adam : 95Bart : 59

Add and remove are used to add and delete elements (keep them unique). When adding elements, use the add () method of set:

>>> s = set([1, 2, 3])>>> s.add(4)>>> print sset([1, 2, 3, 4])

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

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

When deleting elements in 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, the following error occurs when you remove:

>>> s = set([1, 2, 3])>>> s.remove(4)Traceback (most recent call last): File "
 
  ", line 1, in 
  
   KeyError: 4
  
 

So if we want to determine whether an element meets certain conditions, using set is the best choice. the following example:

months = set(['Jan','Feb','Mar','Apr','May','Jun','Jul','Aug','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'>>>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.