Python – Slice List example

Posted on Updated on

In our previous article, we came with examples to iterate list and iterate dictionary. Slicing is an important and commonly used feature in Python. By using slice operation at list, we can get sub-list from original list. In this tutorial we will demonstrate different ways to slice list.

1)  Most popular way to slice List

There are different ways to slice List like from start index, between start and end index or up to end index . Below example demonstrate all above points.

In above example, we have a list which contains numbers from 1 to 10 from which sub lists are create as follow.

  1. In example 1, sub list is created with start index 2.
  2. In example 2, sub list is created between start index and end index which are 3 and 5.
  3. In example 3, sub list is created with end index 5.

Output

2) Slice List in reverse

The above example slices the List in forward direction. However, One can slice list in reverse order. If we use index as -1 in list, the index is treated as end index of the list. So, by using negative sign before the index value you can slice list in reverse. Below example demonstrate slice list in reverse.

Output

3) Slice List using slice Object

The slice(start, stop, increment) object initialization takes in 3 arguments with the last one being the optional index increment. Below example demonstrate list slicing with and without incremental value.

Output

Stay tuned for updates and tutorials !!!

Leave a Reply

Your email address will not be published. Required fields are marked *

Time limit is exhausted. Please reload CAPTCHA.