Python is a popular programming language that supports a vast range of data types such as strings, arrays, tuples and lists. Often python programmers need to be able to access specific parts of data to extract or modify them. This is where slicing is useful. Python Slicing allows you to effortlessly modify strings, lists tuples, and arrays using indexes. In this article, we will learn everything about slicing – what is slicing, how slicing works and some common examples.
Indexing in Python
Before we understand slicing, it is essential to learn about indexing in Python. Slicing completely depends on indexing in Python. Index is the position of a character or element in an indexable data type such as list, array, tuple, or string. It is automatically assigned by Python when you define a data variable. It cannot be explicitly assigned or modified by us.
Indexes can be positive or negative. The positive index begin from 0 assigned to the first character, 1 to next character and so on. The negative indexes start from 0 for the last character, -1 for the penultimate character and so on. Positive and negative indexes allow you to access elements from start or the end respectively. In fact, every character of a data can be accessed using both positive as well as negative indexes. Here is an example of positive as well as negative indexes.
0 1 2 3 4 # positive index
h e l l o # string characters
-4 -3 -2 -1 0 # negative index
As the data is modified the element indexes are also modified. So they are dynamic. For example, if you remove the first character of the above string, the indexes will become different for the other characters.
0 1 2 3 # positive index
e l l o # string characters
-3 -2 -1 0 # negative index
Slicing in Python
Now that we have a good understanding of indexing in Python, let us learn how to use it for slicing. Slicing is basically accessing one or group of elements in an iterable data such as string, array, list or tuple. It can be to insert, modify, or delete these elements. There are several ways to slice data in Python. Bu they all use 3 main parameters – start, stop and step. Start is the starting index of a slice. Stop is the ending index of the slice. Step is a parameter that means the number of elements to be skipped at a time, between start and stop indexes. Each of these parameters is optional and we will see how to use them below.
How Slicing Works in Python
There are 3 different ways to slice in Python
1. Using Index
We typically use index to access a single element from a list or array. Here is an example.
>>> data = 'hello'
>>> data[1]
'e'
Extending this approach, you can also extract a slice of a list. Here is the syntax to do this.
data[start:stop:step]
In the above code, we specify the start index, end index and step. Each of these are optional. Therefore, here are several simple ways to slice your string.
data[start:stop] # from start to stop-1
data[start:] # start till end
data[:stop] # from first item to stop-1
data[:] # copy of whole array
data[start:stop:step] # start to stop, skipping step each time
Here are some examples to demonstrate it. Let us say you have the following string.
data = 'hello'
Here are the different slices, using the previously mentioned syntaxes.
>>> data[2:3] # start at index=2 and stop and index=3
'l'
>>> data[2:] # from index=2 till end
'llo'
>>> data[:3] # from start till index=3
'hel'
>>> data[:] # copy full array
'hello'
>>> data[1:4:2] # start at index=1 and stop and index=4 with step=2
'el'
You can also use negative indexes.
>>> data[-4:-2]
'el'
You can also use negative step as shown below. When the start index is after the stop index, with a negative index, then Python will traverse the string in reverse order. Here -1 is penultimate character and -4 is the first character, and step=-2 so Python starts displaying slice characters in reverse order.
>>> data[-1:-4:-2]
'ol'
2. Using slice() function
Python also provides a constructor slice() to slice a sequence of characters. It also requires the same 3 arguments used above – start, stop and step. Here is its syntax.
slice(start, stop, step)
You need to assign it to a variable and then use it use it directly inside […]. Here are both examples for your reference.
>>> data='hello' >>> x=slice(2,3) >>> data[x] 'l' >>> data[slice(2,3)] 'l'
Let us look at the above examples using slice() function.
>>> data[slice(2,3)] # from index=2 to index=3
'l'
>>> data[slice(2,)] # from index=2 till end
'he'
>>> data[slice(2)] # from index=2 till end
'he'
>>> data[slice(0,3)] # from index=0 till index=3
'hel'
>>> data[slice(0,4,2)] # from index=0 to index=4 with step=2
'hl'
As you can see, slice() offers numerous ways to extract data.
3. Using islice() function
Both the above approaches return a slice object of items. But what if your slice is very large? It will occupy a lot of memory space. In such cases, it is advisable to use islice() function.
Python’s itertools library also provides a built-in function islice() that has same syntax as slice() function, but returns an iterable instead of the slice object. This is useful if you have a large iterable and want to extract a slice iterable, that does not occupy too much memory.
Here is its syntax.
itertools.islice(iterable, start, end, step)
Here is an example to demonstrate it.
>>> a=itertools.islice(data,1,3)
>>> a
<itertools.islice object at 0x032D93F0>
>>> print(a)
<itertools.islice object at 0x032D93F0>
As you can see above, islice() returns an iterable and not a slice object. To display its contents, we use join() function as shown below. It will iterate through the iterable and concatenate its elements to form the slice string.
>>> ''.join(a)
'el'
Slicing Examples
Generally, developers use slicing for simply accessing and extracting a substring from a larger string. But there are many more things that you can do with slicing. Now let us learn some of the common use cases helpful for Python developers.
1. Slice Insert Data
You can use slicing to insert data to a list, array or tuple. Insertion can be done at the start or end of the data as shown below. Here is an example to insert character at the start of a list.
>>> data=['h','e','l','l','o']
>>> data[:0]='s'
>>> data
['s', 'h', 'e', 'l', 'l', 'o']
Here is an example to insert character at the end of the list.
>>> data
['s', 'h', 'e', 'l', 'l', 'o']
>>> data[len(data):]='s'
>>> data
['s', 'h', 'e', 'l', 'l', 'o', 's']
Please note, this does not work on a string since Python strings are immutable.
>>> data=['h','e','l','l','o']
>>> data[:0]='s'
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: 'str' object does not support item assignment
2. Slice Modify Data
Using the above example, you can easily modify specific characters using indexes. Here is the example to modify middle 3 characters.
>>> data=['h','e','l','l','o']
>>> data[1:4]=['g','g','g']
>>> data
['h', 'g', 'g', 'g', 'o']
In the above example, we have used indexes 1 to 4 to select our slice and then replaced it with a new list [‘g’,’g’,’g’].
You can also use the same method to insert data at a specific point.
>>> data=['h','e','l','l','o']
>>> data[4:4]=['g','g','g']
>>> data
['h', 'e', 'l', 'l', 'g', 'g', 'g', 'o']
In the above example, we have used 4:4 slice to indicate we are inserting data at index=4 position. We have inserted list [‘g’,’g’,’g’] at that position.
Please note, strings do not support modification. You can use it for lists, arrays and tuples.
4. Extract Substring Using Slicing
This is the simplest use case to extract substring from a string using indexes. Here are some of the many ways to easily extract substring. We have already covered this earlier.
>>> data=['h','e','l','l','o']
>>> data[2:3]
['l']
>>> data[3:]
['l', 'o']
>>> data[:2]
['h', 'e']
>>> data[0:4:2]
['h', 'l']
5. Reverse String with Slicing
This is perhaps the most interesting use case of slicing. Typically, people think that slicing means extracting one or more characters from a larger string or list. But being able to completely reverse the string or list is something amazing. For this, all you need to do is omit start and stop indexes and use a negative step=-1.
>>> data=['h','e','l','l','o']
>>> data[::-1]
['o', 'l', 'l', 'e', 'h']
The above method works on arrays, lists, strings and tuples since we are not modifying original data.
6. Filter List in Python
You can use the step argument to filter specific items from a sequence of characters. Here is an example to extract the odd characters in list. We use step=2 to skip every other item.
>>> data[::2]
['h', 'l', 'o']
7. Using Negative Indexes
As mentioned earlier, you can also use negative indexes to access specific elements from lists, strings, arrays and tuples. Here are some examples to illustrate it.
>>> data=['h','e','l','l','o']
>>> data[-3:-1]
['l', 'l']
>>> data[-3:]
['l', 'l', 'o']
>>> data[:-1]
['h', 'e', 'l', 'l']
>>> data[-3:-1:2]
['l']
Conclusion
Slicing is a very convenient and powerful way to manipulate indexable data types in Python. It can be used to write concise and clear code. It will save you a lot of development time. Plus it is superfast in performance too. In this article, we have learnt how to slice strings, lists, arrays and tuples in Python. We learnt what is indexing, the different ways to perform slicing and also went through some common use cases. They all work with most Python versions. However, it is important to remember that most slicing operations work with all iterable data like strings, tuples, arrays and lists, except those operations that modify the data. Since strings are immutable, you cannot modify them using slicing operator.
Ubiq makes it easy to visualize data, and monitor them in real-time dashboards. Try Ubiq for free.
Also read:
How to Ask User Input in Python
How to Bind Events to Dynamically Created Elements in JavaScript
How to Password Protect Directory in NGINX
Sreeram Sreenivasan is the Founder of Ubiq. He has helped many Fortune 500 companies in the areas of BI & software development.