The difference between tuples lists and dictionaries in Python

  • 2020-06-01 10:12:32
  • OfStack

In Python, there are three built-in data structures: lists, tuples, and dictionaries.

List 1.

list is a data structure that handles 1 set of ordered items, which means you can store 1 sequence of items in 1 list. Items in the list. The items in the list should be enclosed in square brackets so that python knows that you are specifying a list. Once you create a list, you can add, remove, or search for items in the list. Since you can add or remove items, we say that a list is a mutable data type, that the type can be changed, and that the list can be nested.


print "I don't like these",len(animalslist),'animals...'
for items in animalslist:
print items,
print "\n After the operation "  
# Operation on a list , add , Delete, sort 
del animalslist[0]
for i in range(0,len(animalslist)):
  print animalslist[i],


I don't like these 4 animals...
fox tiger rabbit snake

After the operation

pig rabbit snake tiger

2. A tuple

The tuples are similar to listing 10, but the tuples are immutable. You can't modify tuples. Tuples are defined by comma-separated items in parentheses. Tuples are usually used when a statement or user-defined function can safely adopt a set of values, that is, the value of the used tuple will not change. Tuples can be nested.

>>> zoo=('wolf','elephant','penguin')
>>> zoo.count('penguin')
>>> zoo.index('penguin')
>>> zoo.append('pig')
Traceback (most recent call last):
 File "<stdin>", line 1, in <module>
AttributeError: 'tuple' object has no attribute 'append'
>>> del zoo[0]
Traceback (most recent call last):
 File "<stdin>", line 1, in <module>
TypeError: 'tuple' object doesn't support item deletion

3 a dictionary

A dictionary is similar to an address book where you look up the address and contact details by the contact name; that is, we associate the key (name) with the value (details) at 1. Note that the key must be unique, just like you can't find the correct information if two people happen to have the same name.
Key value pairs are marked in the dictionary in such a way that: d = {key1: value1, key2: value2}. Note that their key/value pairs are separated by colons, and each pair is separated by commas, all of which are enclosed in curly braces. Also, remember that the key/value pairs in the dictionary are in no order. If you want a particular order, you should sort them yourself before you use them.


dict1={'zhang':' nicky ','wang':' Wang baoqiang ','li':' Li bingbing ','zhao':' Zhao wei '}
# Dictionary operations, add, delete, print 
dict1['huang']=' koma '
del dict1['zhao']
for firstname,name in dict1.items():
  print firstname,name


li  Li bingbing 
wang  Wang baoqiang 
huang  koma 
zhang  nicky 

Related articles: