Python 随笔3

                                                 Operation on a list

  • You can think of analogous properties of arrays

  • example of list in Python:

code:

list=['a','b','c','d']
print(list)

results:
['a', 'b', 'c', 'd']

 

3.1.1Accessing list elements

code:

list=['a','b','c','d']
print(list[0])

results:
a

PS:You can manipulate elements in a list by manipulating strings.

3.1.2Index from 0 to the end not 1

code:

list=['a','b','c','d']
print(list[0])
print(list[1])

results:

b

3.1.3Use the individual values in the list

code:

message="The first letter of the alphabet is"+"  "+list[0]
print(message)

results:
The first letter of the alphabet is  a.


3.2 Modify,add and delete elements

The list we have made is already static .

3.2.1Modify the elements

code:

list=['a','b','c','d']
list[0]='A'
print(list)

results:
['A', 'b', 'c', 'd']

3.2.2Add elements tothe list

(1)Add the elements at the end of list

code:

list=['a','b','c','d']
list.append('e')
print(list)

results:
['a', 'b', 'c', 'd', 'e']


PS:We can use the"append()" to fill a empty list

code:

list=[]
list.append('a')
list.append('b')
list.append('c')
list.append('d')
print(list)

results:
['a', 'b', 'c', 'd']

(2)Insert the elements into the litst

code:
 

list.insert(2,'z')
print(list)

results:
['a', 'b', 'z', 'c', 'd']

3.2.3Delete the elements from the list

(1)Use "del()" to delete elements

code:

del list[2]
print(list)

results:

['a', 'b', 'c', 'd']

(2)Use pop() to delete elements

PS:pop(弹出,stack)   Pop the end of the elements in list .

code:

popped_list=list.pop()
print(list)
print(popped_list)

results:
['a', 'b', 'c']
d

PS:The different of the del and pop is that if you want to use the elements and pop it ,please use "pop".If you only want to delete them, please use the del to delete elements.

(3)The element anywhere in the pop-up list

code:

temp=list.pop(2)
print(list)
print(temp)

results:
['a', 'b']
c

(4)Deletes elements by value

code:

print(list)
list.remove('e')
print(list)

results:
['a', 'b', 'c', 'd', 'e']
['a', 'b', 'c', 'd']

Summary:There are four ways to delete the elements from the list.

If need to reprint, please indicate the source, thank you

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值