# 0820 List
Benson Chiu @ FDCS 8th X 7th
<!-- Put the link to this slide here so people can follow -->
slide: https://hackmd.io/@benson-elementary-cpp/SkqpSxBeK#/
---
## How to declare a list?
```python=
a = []
a = [1,2,3,4,5]
a = [1,2,'haha',4,5,[3,3,3,2]]
```
---
## List index
The first element of list $a$ is a[**0**]
```python=
a = [1,2,3,4,5]
print(a[0]) #1
print(a[1]) #2
print(a[4]) #5
```
```python=
print(a[-1]) #5
print(a[-2]) #4
```
---
## List traversal
Method (1)
```python=
a = [1,2,3,4,5]
for i in a:
print(i,end=' ')
```
Method (2)
```python=
a = [1,2,3,4,5]
for i in range(5):
print(a[i])
```
---
## List functions(1)
```python=
a = [1,2,3,4,5]
print(len(a)) #Output the length of the list -> 5
print(min(a)) #1
print(max(a)) #5
print(sum(a)) #15
```
---
## List functions(2)
### Split
* List變數 = 字串.split()
* List變數 = 字串.split(sep字串)
```python=
a = input().split() #input 1 2 3 4 5
print(a) #[1,2,3,4,5]
b = input().split(':') #input 1:2:3:4:5
print(b) #[1,2,3,4,5]
```
---
### Map
new_list = list(map(func,old_list))
- Apply the function to each element, and establish a new list
```python=
a = list(map(int,input().split()))
print(a)
```
---
## List methods
### append, insert
- l.append(value)
- l.insert(index,value)
```python=
l = [1,2,3,4,'haha']
l.append('benson')
print(l)
l.insert(2,'rrrrr')
print(l)
# [1,2,'rrrrr',3,4,'haha','benson']
```
---
### pop
- removed_item = l.pop()
- removed_item = l.pop(index)
```python=
l = [1,2,3,4,5]
la = l.pop() #remove 5
print(la,l)
lb = l.pop(1)
print(lb,l)
```
---
### count
- cnt = l.count(num)
```python=
l = [1,2,2,2,3,3,3,3,4,4,5]
cnt = l.count(3)
print(cnt)
```
---
### sort
- l.sort()
- l.sort(reverse = True)
```python=
l = [4,5,2,5,2,1,1,3,5,7]
l.sort()
print(l)
l.sort(reverse=True)
print(l)
```
---
### copy and slice
- b = a.copy()
- b = a[start : end : step]
```python=
#This is wrong!
a = [1,2,3,4,5]
b = a
b[0] = 6
print(a[0])
#This is correct!
b = a.copy()
b[0] = 6
print(a[0])
#This is correct!
b = a[:]
b[0] = 6
print(a[0])
```
---
```python=
a = [1,2,3,4,5,6,7,8,9,10]
b1 = a[0:9]
b2 = a[0:4]
b3 = a[0:9:2]
print(b1) #[1,2,3,4,5,6,7,8,9]
print(b2) #[1,2,3,4]
print(b3) #[1,3,5,7,9]
```
{"metaMigratedAt":"2023-06-16T07:17:53.491Z","metaMigratedFrom":"YAML","title":"0820 List","breaks":true,"description":"View the slide with \"Slide Mode\".","slideOptions":"{\"spotlight\":{\"enabled\":true}}","contributors":"[{\"id\":\"29625303-a0ab-4215-b54d-35c95f11006b\",\"add\":2478,\"del\":85}]"}