Python programming - basics - lists and tuples

List Example 1:

 (Create, delete, modify)

#  basic operation of list
names = [ ' David '' George '' Peter '' Mark '' ALice ']
print  " Original List: "
print names
del names[1]
print  " Delete second element: "
print names
names[1] =  " Anthony "
print  " Change second element: "
print names

operation result:

Original List:
['David', 'George', 'Peter', 'Mark', 'ALice']
Delete second element:
['David', 'Peter', 'Mark', 'ALice']
Change second element:
['David', 'Anthony', 'Mark', 'ALice']

 

 

List Example 2:

 (Slicing)

    - elements of the Python slicing is used to access a range of

 

#  -*- coding: cp936 -*-

"""
    列表的分片操作
"""
name = list( " Perl ")
print  " Original List From String: "
print name
name[2:] = list( " ice ")
print  " Change elements after second: "
print name
name[2:] = list( " ar ")
print name
number = [1, 2, 3, 5, 6, 7]
print  " Original Number List: "
print number
number.insert(3,  " four ")
print  " Insert before the forth number: "
print number
number.pop()
print  " Pop last number: "
print number
number.pop(0)
print  " Pop first number: "
print number
number.pop(1)
print  " Pop second number: "
print number

 

operation result:

Original List From String:
['P', 'e', 'r', 'l']
Change elements after second:
['P', 'e', 'i', 'c', 'e']
['P', 'e', 'a', 'r']
Original Number List:
[1, 2, 3, 5, 6, 7]
Insert before the forth number:
[1, 2, 3, 'four', 5, 6, 7]
Pop last number:
[1, 2, 3, 'four', 5, 6]
Pop first number:
[2, 3, 'four', 5, 6]
Pop second number:
[2, 'four', 5, 6]

 

Example tuple:

Tuple sequence can not be modified

It can be used as keys in map

 

#  tuple sample
print tuple([1, 2, 3])
print tuple( ' abc ')
print tuple((1, 2, 3))

 

operation result:

(1, 2, 3)
('a', 'b', 'c')
(1, 2, 3)

 

 

Reproduced in: https: //www.cnblogs.com/davidgu/archive/2012/03/15/2397637.html

Guess you like

Origin blog.csdn.net/weixin_33976072/article/details/93802757