---
# System prepended metadata

title: list

---

# list

## 輸入
```python=
#1 
a = [int(i) for i in input().split()]

#2 
a = list(map(int, input().split()))

# 不能這樣寫
a = [map(int, input().split())]
```

## 輸出
```python=
a = [1, 2, 3]

#1 
print(a) #[1, 2, 3]

#2 
print(' '.join(map(str, a))) #1 2 3
```

## 加入、刪除
::: success
`element` : 變數
:::
### 1. append 
```python=
a.append(element) #在a後面插入element
```
ex: 
```python=
a = [1, 2, 3]
a.append(4) # a = [1, 2, 3, 4]
```

### 2. pop
```python=
a.pop(pos) #刪除a中pos位置的元素
```

ex: 
```python=
a = [1, 2, 3]
a.pop(0) # a = [2, 3]
```

### 3. insert 
```python=
a.insert(pos, element) # 在a的pos中加入element
```

ex:
```python=
a = [1, 2, 3]
a.insert(2, 4) # a = [1, 2, 4, 3]
```

### 4. remove
```python=
a.remove(element) #在a中刪除element
```

ex:
```python=
a = [1, 2, 3]
a.remove(1) # a = [2, 3]
```

## 排序

### 1. sort
```python=
a.sort(key=)
```
:::success
key 不一定要加
:::

ex:
```python=
a = [3, 2, 1]
a.sort() # a = [1, 2, 3]
```

## 找尋元素位置
### 1. index
```python=
a.index(element)
```

ex:
```python=
a = [1, 2, 3]
a.index(1) # 0
```

# 補充
## pythonic

### 1. 取區間元素
```python=
a[start : end] # 取a陣列裡面[start, end)
# start 預設第一個，end 預設
```

ex:
```python=
a = [1, 2, 3, 4, 5]
print(a[0:3]) #1, 2, 3
```

### 2. 翻轉陣列
1. reverse
```python=
a.reverse()
```

2. [::-1]
ex. 
```python=
a = [1, 2, 3]
a = a[::-1] # a = [3, 2, 1]
```

### 3. 輸出進階版
```python=
a = [1, 2, 3]

#1 
print(*a) #1 2 3

#2
print(*a, sep = ',') #1, 2, 3
```

