In this list slicing in Python tutorial, we will learn what is slicing of lists in Python, what is the purpose of list slicing, the difference between slicing and indexing lists, and how Python slicing works with code examples to illustrate.
What is slicing of lists in Python?
Slicing of lists in Python refers to accessing a specific part or subset of the list for a particular operation while the original list stays unchanged. The slicing operator in Python can work with three parameters, but two of them can be left out depending on the situation.
Slice notation is the syntax for the Python slice command. This expanded indexing syntax retrieves a range of values from the sliced list.
We slice a list using a colon inside the square brackets to define a start, end, and step or variable range. When entering slice notation, the following syntax may be used:
- Start position: is the list index where slicing starts.
- End position: is the list index where slicing ends.
- The increment – indicates the number of step sizes.
Also read: Python Uppercase Method With Examples
What is the purpose of list slicing?
Python’s slicing functionality offers access to subsets of sequences such as strings, tuples, and lists. Additionally, you can use them to alter or delete the objects in mutable sequences, such as lists.
Slices can be applied to objects from third-party libraries, such as NumPy arrays, Pandas series, and data frames.
For additional information, check out the slice
() built-in function in the Python documentation.
What is the difference between slicing and indexing of list?
The difference between indexes and slices of lists is that indexing refers to an element of an iterable by its position in the iterable, while slicing is getting a subset of elements from an iterable based on their indexes.
How does Python slicing work?
You can use the slice()
built-in function in Python to slice a list.
The slice()
function returns an object of type slice. A slice object specifies how to divide a sequence. You can determine where the slicing begins and ends. You can optionally specify the step that permits only every other item to be sliced.
Return a slice object representing the set of indices specified by range(start, stop, step). The start and step arguments default to None.
Built-in Functions
Slicing
In Python, list slicing is a widespread practice, and it is the method most frequently employed by programmers to solve problems efficiently. A slice extracts elements based on where it starts and stops.
Slicing is the indexing syntax used to extract a subset of a list.
In order to access a subset of the elements of a list, it must be sliced. This can be accomplished using the simple slicing operator, colon (:
).
The following program converts the above example to Python code:
list1 = ['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i']
print(list1[1:8:2])
Output:
['b', 'd', 'f', 'h']
It returns your sliced list with the first item as the “start” index and the last item as the “stop” index.
Note: The value after the position 8 is not included.
Example 1:
list1 = ['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i']
print(list1[1:7:2]) # this code will printout the index from 1 to 7 by 2
print(list1[::2]) # this code will printout all the odd values
print(list1[::]) # empty parameters will printout all the values.
Output:
['b', 'd', 'f']
['a', 'c', 'e', 'g', 'i']
['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i']
If an argument such as Start position, End position, or The increment is left blank, default values will be used.
Example 2:
list1 = ['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i']
print(list1[::-1]) # This will print all the values in reverse
print(list1[::-2]) # This will print all the values in reverse by 2 starting in index 0.
print(list1[:1:-2]) # This will print all the values up to value 1 in reverse by 2
Output:
['i', 'h', 'g', 'f', 'e', 'd', 'c', 'b', 'a'] ['i', 'g', 'e', 'c', 'a'] ['i', 'g', 'e', 'c']
Using a negative integer as the increment argument will result in reversing a list. The Start and End positions are left blank. If the increment value is negative, the Start position and End position values must be selected from an inverted list.
Example 3:
list1 = ['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i']
print(list1[1:1:1])
print(list1[20::5])
print(list1[-2:-2:-2])
Output:
[]
[]
[]
If any slicing expressions do not make sense or cannot be computed, then empty lists are produced.
Example 4:
list1 = ['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i']
list1[3:5] = ['j', 'k', 'l']
print(list1)
list1[:3] = []
print(list1)
Output:
['a', 'b', 'c', 'j', 'k', 'l', 'f', 'g', 'h', 'i']
['j', 'k', 'l', 'f', 'g', 'h', 'i']
With Python’s slice assignment operations, we can do a lot of cool things to an existing list, including editing or deleting list elements.
Example 5:
list1 = ['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i']
new_list1 = list1[:2] + list1[8:]
print(new_list1)
new_list1 = list1[::3] + list1[2::3]
print(new_list1)
Output:
['a', 'b', 'i']
['a', 'd', 'g', 'c', 'f', 'i']
It is possible to build a new list or modify an existing one by concatenating sliced lists.
Positive Indexes
We may simply locate any element by its position using indexing. This is useful for using locations from the beginning of a list.
For example, we want to select the letter 'f'
, 'g'
, and 'h'
in a list. The image below shows how a list element can be sliced using positive indexes.
Example Program:
list1 = ['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i']
print(list1[5:8])
Output:
['f', 'g', 'h']
Negative Indexes
You can also specify negative indexes while slicing a list.
For example, we want to select the letter 'f'
, 'g'
, and 'h'
in a list. The image below shows how a list element can be sliced using negative indexes.
Example Program:
list1 = ['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i']
print(list1[-4:-1])
Output:
['f', 'g', 'h']
You can also try to reverse a list using the negative step indexes.
Example:
list1 = ['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i']
print(list1[::-1])
Output:
['i', 'h', 'g', 'f', 'e', 'd', 'c', 'b', 'a']
Summary
This article shows how list slicing in Python works, with supporting examples and illustrations. It also discussed the difference between slicing and indexing lists and the positive and negative indexes.
We hope this tutorial helps you learn the fundamentals of Python list slicing and indexing.