How to get sub list by slicing a Python List

Slice a list

Slicing means accessing a range of list. We can do slicing by providing two indices separated by a colon.

The first value is the start index and the second value is the to index. The start index is inclusive and to index is exclusive.


numbers = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10] 
print numbers[3:6] 
print numbers[0:1] 

The code above generates the following result.

Just as indexing we can do slicing from the right of a list.

To slice from the end of a list we can omit the second index and use negative value for the first index.


numbers = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10] 
print numbers[-3:-1] 

The code above generates the following result.

If the leftmost index in a slice comes later in the sequence than the second one, the result is an empty sequence.

We can use a shortcut: If the slice continues to the end of the sequence, you may simply leave out the last index:


numbers = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10] 
print numbers[-3:] 

The same thing works from the beginning:


numbers = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10] 
numbers[:3] 

To copy the entire sequence, you may leave out both indices:


numbers = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10] 
print numbers[:] 

Slicing is very useful for extracting parts of a list. The following code splits up a URL of the form http://www.something.com.


url = 'http://www.java2s.com.com'
domain = url[11:-4] 
print "Domain name: " + domain 

The code above generates the following result.





















Home »
  Python »
    Data Types »




Data Types
String
String Format
Tuple
List
Set
Dictionary