Basic Slicing

suggest change

For any iterable (for eg. a string, list, etc), Python allows you to slice and return a substring or sublist of its data.

Format for slicing:

iterable_name[start:stop:step]

where,

Examples:

a = "abcdef"
a            # "abcdef" 
             # Same as a[:] or a[::] since it uses the defaults for all three indices
a[-1]        # "f"
a[:]         # "abcdef" 
a[::]        # "abcdef" 
a[3:]        # "def" (from index 3, to end(defaults to size of iterable)) 
a[:4]        # "abcd" (from beginning(default 0) to position 4 (excluded)) 
a[2:4]       # "cd" (from position 2, to position 4 (excluded))

In addition, any of the above can be used with the step size defined:

a[::2]       # "ace" (every 2nd element)
a[1:4:2]     # "bd" (from index 1, to index 4 (excluded), every 2nd element)

Indices can be negative, in which case they’re computed from the end of the sequence

a[:-1]     # "abcde" (from index 0 (default), to the second last element (last element - 1))
a[:-2]     # "abcd" (from index 0 (default), to the third last element (last element -2))
a[-1:]     # "f" (from the last element to the end (default len())

Step sizes can also be negative, in which case slice will iterate through the list in reverse order:

a[3:1:-1]   # "dc" (from index 2 to None (default), in reverse order)

This construct is useful for reversing an iterable

a[::-1]     # "fedcba" (from last element (default len()-1), to first, in reverse order(-1))

Notice that for negative steps the default end_index is None (see http://stackoverflow.com/a/12521981 )

a[5:None:-1] # "fedcba" (this is equivalent to a[::-1])
a[5:0:-1]    # "fedcb" (from the last element (index 5) to second element (index 1)

Feedback about page:

Feedback:
Optional: your email if you want me to get back to you:


Indexing and Slicing:
* Basic Slicing

Table Of Contents
2 Filter
3 List
7 Loops
19 Indexing and Slicing
22 Reduce
27 Classes
31 Set
42 Tuple
45 Enum
62 Sockets
89 urllib
92 Idioms
104 Stack
105 Profiling
109 Logging
111 os module
118 Mixins
120 ArcPy
126 Arrays
132 2to3 tool
135 Unicode
138 Neo4j
140 Curses
141 Templates
145 heapq
146 tkinter
154 Audio
155 pyglet
157 ijson
160 Flask
161 Groupby
163 pygame
165 hashlib
166 Gzip
167 ctypes
185 pyaudio
186 shelve