# 切片 #

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

## 遍历 #

### enumerate #

``````a = ["a", "b", "c", "d"]

# index & value
for i in xrange(len(a)):
print i, a[i]

# iterate with index
for i, el in enumerate(a):
print i, el

# i 从 1 开始
for i, el in enumerate(a, 1):
print i, el
``````

## step 为负数 #

### 字符串反转 #

``````letter[::-1]
``````

### 为什么 s[:-1:-1] 是空 #

• 倒数第二个作为 start，end 默认，step 是 -1
• 也就是：`s[-2::-1]`
``````s[i:j:k]
``````
• If i or j is negative, the index is relative to the end of sequence s:

• `len(s) + i` or `len(s) + j` is substituted.
• But note that -0 is still 0.
• The slice of s from i to j with step k

• is defined as the sequence of items with index x = i + n*k
• such that 0 <= n < (j-i)/k.
• the indices are i, i+k, i+2k, i+3k and so on,

• stopping when j is reached (but never including j).
• When k is positive, i and j are reduced to len(s) if they are greater.

• When k is negative, i and j are reduced to len(s) - 1 if they are greater.

• If i or j are omitted or None, they become “end” values (which end depends on the sign of k).

• k cannot be zero.

• If k is None, it is treated like 1.
• `s[:]`

• 等同于 `s[::]`
• 等同于 `s[None:None:None]`
• 等同于 `s[0:len(s):1]`
• `s[::-1]`

• 等同于 `s[None:None:-1]`
• 等同于 `s[len(s)-1:-len(s)-1:-1]`
• 包括 start，所以 start 从 `len(s)-1` 开始, 就是 s[-1]
• 不包括 end, 所以 end 到 `-len(s)-1`, 实际上就是到 `-len(s)`, 也就是 s
• `s[:-1:-1]`

• 等同于 `s[len(s)-1:-1:-1]`
• 等同于 `s[len(s)-1:len(s)-1:-1]`

## sequence 乘法 #

• `s * n``n * s`
• equivalent to adding s to itself n times
• items in the sequence s are not copied
• they are referenced multiple times
• Values of n less than 0 are treated as 0
• which yields an empty sequence of the same type as s
``````>>> lists = [[]] * 3
>>> lists
[[], [], []]
>>> lists.append(3)
>>> lists
[, , ]
``````