Difference between indexing and slicing in Python


In this article, we will explain to you the differences between indexing and slicing in python.

Indexing and slicing are applicable only to sequence data types. The order in which elements are inserted is preserved in sequence type, allowing us to access its elements via indexing and slicing.

To summarise, Python's sequence types are list, tuple, string, range, byte, and byte arrays. And indexing and slicing are applicable to all of these types.

Indexing

The term "indexing" refers to refers to an element of an iterable based on its position inside the iterable.

The indexing begins from 0. The first element in the sequence is represented by index 0.

Negative indexing begins from -1. The last element in the sequence is represented by index -1.

Each character in a string corresponds to an index number, and each character can be accessed by its index number. There are two ways to access characters in a String

  • Accessing string characters using positive indexing

  • Accessing string characters using negative indexing

                     T  U  T  O  T  I  A  L  S
Positive Indexing    0  1  2  3  4  5  6  7  8
Negative indexing   -9 -8 -7 -6 -5 -4 -3 -2 -1

Accessing string characters using positive indexing

In this case, we pass a Positive index (that we wish to access) in square brackets. The index number sequence begins with index number 0. (represents the first character of a string).

Example

# input string inputString = "Hello tutorialspoint python" print("0th index character:", inputString[0]) print("7th index character", inputString[7]) print("12th index character:", inputString[12])
('0th index character:', 'H') ('7th index character', 'u') ('12th index character:', 'a')

Output

0th index character: H
7th index character u
12th index character: a

Accessing string characters using negative indexing

We pass the Negative index (we wish to access) in square brackets in this type of indexing. The index number starts at -1 in this case (that represents the last character of a string).

Example

# input string inputString = "Hello tutorialspoint python" print("last index character:", inputString[-1]) print("6th index character from last:", inputString[-6])
('last index character:', 'n') ('6th index character from last:', 'p')

Output

last index character: n
6th index character from last: p

Indexing in List

Example

# input list inputList =[1, 4, 8, 6, 2] print("Element at index 2:", inputList[2]) print("last element of an input list:", inputList[-1])
('Element at index 2:', 8) ('last element of an input list:', 2)

Output

Element at index 2: 8
last element of an input list: 2

NOTE

When we attempt to use an index which does no exist or too large, it throws an IndexError

Example

# input list inputList =[1, 4, 8, 6, 2] # printing the element at index 10 of a input list # throws an IndexError as the index 10 doesn't exist in the input list print("Element at index 10:", inputList[10])
Traceback (most recent call last): File "main.py", line 5, in <module> print("Element at index 10:", inputList[10]) IndexError: list index out of range

Output

Traceback (most recent call last):
File "main.py", line 5, in <module>
print("Element at index 10:", inputList[10])
IndexError: list index out of range

Slicing

The term "slicing" refers to obtaining a subset of elements from an iterable based on their indices.

We create a substring by slicing a string, which is effectively a string that exists within another string. We utilize slicing when we only need a portion of the string and not the entire string.

Syntax

string[start : end : step]

Parameters

start - index from where to start
end - ending index
step - numbers of jumps/increment to take between i.e stepsize

Slicing in strings

# input string inputString = "Hello tutorialspoint python" print("First 4 characters of the string:", inputString[: 4]) print("Alternate characters from 1 to 10 index(excluded):", inputString[1 : 10 : 2]) print("Alternate characters in reverse order from 1 to 10 index(excluded):", inputString[-1 : -10 : -2])
('First 4 characters of the string:', 'Hell') ('Alternate characters from 1 to 10 index(excluded):', 'el uo') ('Alternate characters in reverse order from 1 to 10 index(excluded):', 'nhy n')

Output

First 4 characters of the string: Hell
Alternate characters from 1 to 10 index(excluded): el uo
Alternate characters in reverse order from 1 to 10 index(excluded): nhy n

Tuple Slicing

We can use tuple slicing. It is similar to how we use strings and lists. Tuple slicing is used to obtain a variety of items. We also use the slicing operator to perform tuple slicing. The slicing operator can be represented by the syntax

Syntax

[start:stop:step]

Example

# Input tuple givenTuple = ("Welcome", "this", "is", "TutorialsPoint", "Website", 10) # Slicing with start and stop values(indices) print('Tuple slicing from index 1 to index 6 :', givenTuple[1:6]) # Slicing with only stop values(indices) print("Tuple slicing till index 7: ", givenTuple[:7]) # Slicing with only start value(indices) print("Tuple slicing from index 2 is:", givenTuple[2:]) # Slicing without any start and stop values print("Tuple slicing without any start and stop values:", givenTuple[:]) # Slicing in reverse order print("Tuple slicing in reverse order:", givenTuple[::-1])
('Tuple slicing from index 1 to index 6 :', ('this', 'is', 'TutorialsPoint', 'Website', 10)) ('Tuple slicing till index 7: ', ('Welcome', 'this', 'is', 'TutorialsPoint', 'Website', 10)) ('Tuple slicing from index 2 is:', ('is', 'TutorialsPoint', 'Website', 10)) ('Tuple slicing without any start and stop values:', ('Welcome', 'this', 'is', 'TutorialsPoint', 'Website', 10)) ('Tuple slicing in reverse order:', (10, 'Website', 'TutorialsPoint', 'is', 'this', 'Welcome'))

Output

Tuple slicing from index 1 to index 6 : ('this', 'is', 'TutorialsPoint', 'Website', 10)
Tuple slicing till index 7:  ('Welcome', 'this', 'is', 'TutorialsPoint', 'Website', 10)
Tuple slicing from index 2 is: ('is', 'TutorialsPoint', 'Website', 10)
Tuple slicing without any start and stop values: ('Welcome', 'this', 'is', 'TutorialsPoint', 'Website', 10)
Tuple slicing in reverse order: (10, 'Website', 'TutorialsPoint', 'is', 'this', 'Welcome')

Indexing vs Slicing Differentiation

The following table shows the key differences between indexing and slicing in python −

Indexing Slicing
It returns only 1 item It returns a new list/tuple
An IndexError will be thrown if you attempt to use an index that is too large. When used for slicing, out-of-range indexes are handled gently.
We cannot change the length of the list by item assignment in indexing. We can change the length of the list or even clear it by assigning items to slicing.
We can assign a single element or an iterable to indexing. When we assign a single element to slicing, we get a TypeError. It will only accept iterables.

Conclusion

With the help of examples, we learned about the differences between indexing and slicing in Python.

Updated on: 15-Sep-2022

9K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements