# 货柜¶

## 列表¶

```>>> list()
[]
```

```>>> []
[]
```

```>>> list([1, 2, 3])
[1, 2, 3]
```

```>>> [1, 2, 3]
[1, 2, 3]
```

```>>> x = [1, 2, 3]
>>> print(x[1])
2
```

```>>> x = [1, 2, 3]
>>> x[1] = 4
>>> print(x)
[1, 4, 3]
```

```>>> x = [1, 2, 3, 4, 5]
>>> print(x[-1])
5
>>> print(x[-2])
4
```

```list[start:end:step]
```

```>>> x = ['zero', 'one', 'two', 'three', 'four']
>>> print(x[2:])
['two', 'three', 'four']
>>> print(x[:3])
['zero', 'one', 'two']
>>> print(x[1:3])
['one', 'two']
>>> print(x[::2])
['zero', 'two', 'four']
>>> print(x[::-1])
['four', 'three', 'two', 'one', 'zero']
>>> print(x[-2:])
['three', 'four']
```

```>>> x = [1, 2, 3]
>>> print(x)
[1, 2, 3]
>>> x.append(4)
>>> print(x)
[1, 2, 3, 4]
```

```>>> x = [1, 2, 3]
>>> print(x)
[1, 2, 3]
>>> x.insert(0, -1)
>>> print(x)
[-1, 1, 2, 3]
>>> x.insert(1, 0)
>>> print(x)
[-1, 0, 1, 2, 3]
```

```>>> [1, 'two', ['three', 4]]
[1, 'two', ['three', 4]]
```

## 元组¶

```>>> tuple([1, 2, 3])
(1, 2, 3)
>>> (1, 2, 3)
(1, 2, 3)
```

```>>> x = (1, 2, 3)
>>> print(x[1])
2
```

```>>> x = (1, 2, 3)
>>> x[1] = 4
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: 'tuple' object does not support item assignment
```

## 集合¶

```>>> set()  # This one is empty
set()
>>> set([1, 2, 2, 3, 3, 'three'])
{1, 2, 3, 'three'}
>>> {1, 2, 2, 3, 3, 'three'}
{1, 'three', 2, 3}
```

```>>> x = {1, 2, 3}
>>> print(x)
{1, 2, 3}
>>> print(x)
{1, 2, 'four', 3}
```

`Sets` 此外，还支持许多您在 set in mathematics 。有关详细信息，请参阅Python文档。

## 词典¶

```>>> dict()
{}
>>> {}
{}
>>> x = {'One': 1, 'two': 2, 'THREE': ['A', 'list', 'of', 'strings']}
{'THREE': ['A', 'list', 'of', 'strings'], 'One': 1, 'two': 2}
```

```>>> x = {'One': 1, 'two': 2, 'THREE': ['A', 'list', 'of', 'strings']}
>>> x['One']
1
>>> x['THREE']
['A', 'list', 'of', 'strings']
```

```>>> x = {'One': 1, 'two': 2, 'THREE': ['A', 'list', 'of', 'strings']}
>>> x['four']
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
KeyError: 'four'
```

```>>> x = {'One': 1, 'two': 2, 'THREE': ['A', 'list', 'of', 'strings']}
>>> x.get('two', 'fallback')
2
>>> x.get('four', 'fallback')
'fallback'
```

## 常见操作¶

### 长度¶

```>>> x = [1, 2, 3]
>>> len(x)
3
>>> x = (1, 2)
>>> len(x)
2
>>> x = set([1, 2, 2, 3, 3, 'three'])
>>> len(x)
4
>>> x = {'One': 1, 'two': 2, 'THREE': ['A', 'list', 'of', 'strings']}
>>> len(x)
3
```

### 会员资格检查¶

```>>> x = [1, 2, 3]
>>> 2 in x
True
```

```>>> x = {
...    'one': 'two',
...    3: 4
... }
>>> 'one' in x
True
>>> 'two' in x
False
>>> 3 not in x
False
>>> 4 not in x
True
```

## 摘要¶

• 使用 `lists` 如果顺序很重要，并且您可能需要修改容器。

• 使用 `tuples` 如果订单很重要并且容器是固定的。

• 使用 `sets` 如果顺序并不重要，并且您希望确保容器内的唯一性。

• 使用 `dictionaries` 如果要存储键-值对，请执行以下操作。