02List的使用

When we talk about storing multiple values in a container-like data structure, the first thing that comes to mind is a list.

You can initialize a list as:

arr = list()
# or simply
arr = [] 

or with a few elements as:

arr = [1,2,3] 

Elements can be accessed easily similar to most programming languages:

print arr[0]
# result is 1 print arr[0] + arr[1] + arr[2] # result is 6 

Lists in Python are very versatile. You can add almost anything in a Python list.

In Python, you can create a list of any objects: strings, integers, or even lists. You can even add multiple types in a single list!

Let's look at some of the methods you can use on list.

1.) append(x)

Adds a single element x to the end of a list.

arr.append(9) print arr # prints [1, 2, 3, 9] 

2.) extend(L)

Merges another list L to the end.

arr.extend([10,11]) print arr # prints [1, 2, 3, 9, 10, 11] 

3.) insert(i,x) 
Inserts element x at position i.

arr.insert(3,7) print arr # prints [1, 2, 3, 7, 9, 10, 11] 

4.) remove(x) 
Removes the first occurrence of element x.

arr.remove(10) arr # prints [1, 2, 3, 7, 9, 11] 

5.) pop() 
Removes the last element of a list. If an argument is passed, that index item is popped out.

temp = arr.pop() print temp # prints 11 

6.) index(x) 
Returns the first index of a value in the list. Throws an error if it's not found.

temp = arr.index(3) print temp # prints 2 

7.) count(x) 
Counts the number of occurrences of an element x.

temp = arr.count(1) print temp # prints 1 

8.) sort() 
Sorts the list.

arr.sort()
print arr # [1, 2, 3, 7, 9] 

9.) reverse() 
Reverses the list.

arr.reverse()
print arr # [9, 7, 3, 2, 1]

转载于:https://www.cnblogs.com/passion-sky/p/8532342.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值