python List Dictionary Tuple Simple Usage Example

  • 2021-07-13 05:56:43
  • OfStack

This article illustrates the simple usage of python list, dictionary and tuple. Share it for your reference, as follows:

List


#_*_ coding:utf-8 _*_
#  List, defined in square brackets, can be sliced. 
# It has no fixed type constraint, that is, it can contain different data types. 
L=[1,'abc',2.3]
print len(L)
print '*'*40
L.append('mengtianwxs')
print(L)
print '*'*40
L.pop(0)
print(L)
print '*'*40
L.sort()
print(L)
L.reverse()
print(L)
print '*'*40
# Deletes the specified item 
L.remove('abc')
print(L)

This is the result of the output

3
****************************************
[1, 'abc', 2.3, 'mengtianwxs']
****************************************
['abc', 2.3, 'mengtianwxs']
****************************************
[2.3, 'abc', 'mengtianwxs']
['mengtianwxs', 'abc', 2.3]
****************************************
['mengtianwxs', 2.3]

Dictionaries are not sequences, they are mappings.


#_*_ coding:utf-8 _*_
dir={'a':'xiaojing','b':'xiaoli','c':'xiaolong'}
# If you want to output in order in the dictionary, you must sort the keys first. 
KS=dir.keys()
KS.sort()
for key in KS:
  print dir[key],

This is the output:

xiaojing xiaoli xiaolong


#_*_ coding:utf-8 _*_
dir={'a':'xiaojing','b':'xiaoli','c':'xiaolong'}
# If you want to output in order in the dictionary, you must sort the keys first. 
KS=dir.keys()
#KS.sort()
# This is the output after the annotation, which is obviously out of order 
for key in KS:
  print dir[key],
#output xiaojing xiaolong xiaoli

Tuple

Tuples are objects defined between (). It is a list that cannot be changed and is a sequence.


#_*_ coding:utf-8 _*_
t=(1,2,3,4,5,6)
print len(t)
# Gets the first in the tuple 1 Elements 
print t[0]
# Gets a tuple with a value of 1 Index value of 
print t.index(1)
# In the statistical tuple 2 Number of occurrences 
print t.count(2)
# Tuples do not support growth or decrease and cannot be used append Add an element. 
# 6
# 1
# 0
# 1

For more readers interested in Python related contents, please check the topics of this site: "Summary of Python Function Use Skills", "Summary of Python List (list) Operation Skills", "Summary of Python Dictionary Operation Skills", "Python Data Structure and Algorithm Tutorial", "Summary of Python String Operation Skills" and "Introduction and Advanced Classic Tutorial of Python"

I hope this article is helpful to everyone's Python programming.


Related articles: