The difference between indexing and slicing in Python

Differences between Indexing and Slicing in Python

In this article, we will explain the difference between indexing and slicing in Python.

Indexing and slicing only apply to sequence data types. The order in which elements are inserted into a sequence is preserved, allowing us to access its elements through indexing and slicing.

In summary, Python’s sequence types include lists, tuples, strings, ranges, bytes, and byte arrays. Indexing and slicing apply to all of these types.

Indexing

The term “index” refers to referencing an element based on its position within an iterable object.

Indexing starts at 0. The first element in a sequence is represented by index 0.

Negative indices start at -1. The last element in a sequence is represented by index -1.

Each character in a string is associated with an index number, and each character can be accessed using its index number. There are two ways to access characters in a string.

  • Accessing string characters using positive indices
  • Accessing string characters using negative indices

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

Accessing characters in a string using positive indices

In this case, we pass a positive index (the index we want to access) within square brackets. The index number sequence starts at 0 (representing the first character of the string).

Example

# Input string
inputString = "Hello tutorialspoint python"

print("Character at index 0:", inputString[0])

print("Character at index 7:", inputString[7])

print("Character at index 12:", inputString[12])

('Character at index 0:', 'H')
('Character at index 7:', 'u')
('Character at index 12:', 'a')

Output

Character at index 0: H
Character at index 7: u
Character at index 12: a

Accessing string characters using negative indices

In this type of indexing, we pass the negative index (the index we want to access) within square brackets. In this case, the index starts at -1 (indicating the last character in the string).

Example

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

Output

The last index character: n
The sixth index character from the back: p

Index in a list

Example

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

Output

Element at index 2: 8
Last element of the input list: 2

Note

When we try to use an index that does not exist or is too large, an error message is thrown. IndexError

Example

# Input list
inputList =[1, 4, 8, 6, 2]
# Print the element at index 10 in the input list
# Since index 10 does not exist in the input list, an IndexError is raised
print("The element at index 10:", inputList[10])
Traceback (most recent call last):
File "main.py", line 5, in <module>
print("The 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("The element at index 10:", inputList[10])
IndexError: list index out of range

Slicing

The term “slicing” refers to getting a subset of elements from an iterable object based on their index.

Slicing creates a substring, which is essentially a string that exists within another string. We use slicing when we need only a portion of a string rather than the entire string.

Syntax

string[start : end : step]

Parameters

start - Starting index
end - Ending index
step - Number of jumps/increments to make, i.e., step size

String Slicing

# Input string
inputString = "Hello tutorialspoint python"
print("First 4 characters of string:", inputString[: 4])
print("Every character from index 1 to index 10 (not included):", inputString[1 : 10 : 2])
print("Every character from index 1 to index 10 (not included) in reverse order:", inputString[-1 : -10 : -2])
('The first 4 characters of the string:', 'Hell')
('Every character from index 1 to index 10 (not included):', 'el uo')
('Every character from index 1 to index 10 (not included) in reverse order:', 'nhy n')

Output

The first 4 characters of the string: Hell
Every character from index 1 to index 10 (not included): el uo
Every character from index 1 to index 10 (not included) in reverse order: nhy n

Tuple Slicing

We can use tuple slicing. Similar to how we use strings and lists, tuple slicing is used to retrieve various items. We also use the slice operator to perform tuple slicing. The slicing operator can be expressed using the syntax

Syntax

[start:stop:step]

Example

# Input tuple
givenTuple = ("Welcome", "this", "is", "TutorialsPoint", "Website", 10)
# Slice using both start and stop values (indexes)
print('Tuple slicing from index 1 to index 6:', givenTuple[1:6])
# Slice using only the stop value (index)
print("Tuple slicing till index 7: ", givenTuple[:7])
# Slice using only the start value (index)
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 until 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')

Differences between indexing and slicing

The following table shows the main differences between indexing and slicing in Python.

Indexing Slicing
It returns only 1 item It returns a new list/tuple
If you try to use an index that is too large, an IndexError will be thrown. Handle out-of-range indices when used with slicing.
We cannot change the length of a list by assigning items to an index. By assigning items to a slice, we can change the length of a list or even clear it.
We can assign either a single element or an iterable to an index. When we assign a single element to a slice, a TypeError occurs. It only accepts iterables.

Conclusion

Through examples, we learned the difference between indexing and slicing in Python.

Leave a Reply

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