---
title: "Python slice"
author: "fairy_xzc"
date: "2016-10-08T12:08:16Z"
tags: []
categories: ["编程语言"]
slug: "python-slice"
draft: false
lastmod: "2016-10-08T12:06:07Z"
id: 2328911
url: "https://agilestyle.iteye.com/blog/2328911"
---

**原创转载请注明出处：[http://agilestyle.iteye.com/blog/2328911](/blog/2328911)**

 

```
L = ['GuanYu', 'ZhangFei', 'ZhaoYun', 'MaChao', 'HuangZhong']

# get the first 3 elements
# ['GuanYu', 'ZhangFei', 'ZhaoYun']
print(L[0:3])
# ['GuanYu', 'ZhangFei', 'ZhaoYun']
print(L[:3])

# get the last 2 elements
# ['MaChao', 'HuangZhong']
print(L[-2:])
# ['MaChao']
print(L[-2:-1])
```

Console Output

![](http://dl2.iteye.com/upload/attachment/0120/4550/0d544f9a-1488-3c02-995c-963f0ca9d5d9.png)

 

**Python支持L\[-1]取倒数第一个元素, 记住倒数第一个元素的索引是-1**

```
L = list(range(100))
# get the first 10 elements
print(L[:10])
# get the last 10 elements
print(L[-10:])
# get 11 - 20 elements
print(L[10:20])
# 前10个数，每2个取一个
# [0, 2, 4, 6, 8]
print(L[:10:2])
# 所有数，每5个取一个
# [0, 5, 10, 15, 20, 25, 30, 35, 40, 45, 50, 55, 60, 65, 70, 75, 80, 85, 90, 95]
print(L[::5])
# 只写[:]就可以原样复制一个list
print(L[:])
```

Console Output

![](http://dl2.iteye.com/upload/attachment/0120/4552/063ecb40-4e9c-3423-b1c2-a9eab1e48ba9.png)  
   
tuple也是一种list，唯一区别是tuple不可变

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

字符串'xxx'也可以看成是一种list，每个元素就是一个字符

```
str1 = 'ABCDEFG'[:3]
# ABC
print(str1)
# ACEG
str2 = 'ABCDEFG'[::2]
print(str2)
```

Console Output

![](http://dl2.iteye.com/upload/attachment/0120/4556/e213a5f0-f969-391b-9306-0b5f71b11f81.png)