Indexing vs Slicing in Python

Get to know about indexing and slicing

Photo by Bianca Ackermann on Unsplash

Indexing and Slicing:

In python sequence data types, we can access elements by indexing and slicing. Sequence data types are strings, list, tuple, range objects. Let’s learn about indexing and slicing in detail in this article.


Topics covered in this article:

Image by Author

What are Indexing and Slicing?

Indexing: Indexing is used to obtain individual elements.

Slicing: Slicing is used to obtain a sequence of elements.

Indexing and Slicing can be be done in Python Sequences types like list, string, tuple, range objects.

Indexing

Indexing starts from 0. Index 0 represents the first element in the sequence.

Negative indexing starts from -1. Index -1 represents the last element in the sequence.

Indexing in string

Indexing in strings(Image Source: Author)

Example of Indexing in strings

s="Python"
print (s[0])#Output:P
print (s[-1])#Output:n
print (s[-2])#Output:o

Indexing in List

Indexing in List(Image Source: Author)

Example of Indexing in List

list_=[10,20,30,40,50]
print (list_[0])#Output:10
print (list_[-1])#Output:50
print (list_[-2])#Output:40

Indexing in tuple and range object

#Indexing - tuple
t=(1,2,3,4,5)
print (t[0])#Output:1
print (t[-1])#Output:5
print (t[-2])#Output:4

#Indexing - range object
r=range(5)
print (r[0])#Output:0
print (r[-1])#Output:4
print (r[-2])#Output:3

IndexError

Attempting to use an index that is too large will result in an IndexError.

#Indexing - tuple
t=(1,2,3,4,5)
print (t[-6])#Output:IndexError: tuple index out of range


#Indexing - range object
r=range(5)
print (r[-7])#Output:IndexError: range object index out of range


#Indexing - List
n=[1,2,3,4,5]
print (n[6])#Output:IndexError: list index out of range


#Indexing -string
s="python"
print (s[7])#Output:IndexError: string index out of range

Assignment to Indexing

Immutable objects:

Assigning to an indexed position for immutable objects like strings, tuple, range object will raise a TypeError.

Item assignment in tuple, strings, range object:

s="Python"
s[0]="j"
#Output:TypeError: 'str' object does not support item assignment

t=(1,2,3)
t[2]=7#Output:TypeError: 'tuple' object does not support item assignment

r=range(5)
r[0]=10
#Output:TypeError: 'range' object does not support item assignment

If a tuple contains mutable objects like a list, we can do item assignment for that list.

t=(1,2,[3])
#Item assignment supported for list element inside tuple.
t[2][0]=7
print (t)#Output:(1, 2, [7])

Mutable objects:

Item assignment is supported in List(mutable object).

num=[1,2,3,4,5]
num[2]=99
#list supports item assignment
print (num)
#Output:[1, 2, 99, 4, 5]


colors=["red","blue","green"]
colors[1]="yellow"
print (colors)
#Output:['red', 'yellow', 'green']

Slicing:

  • Slicing (Range Of Indexes):

We can specify a range of indexes.

s[i:j:k] — slice of s from i to j with step k

Slicing Strings

slicing allows you to obtain substring
1. s[1:3] — Returns element from the first index to the third index(excluded).

s=”Python”
print (s[1:3])
#Output:yt

2. s[0:3]-Returns element from the beginning of the string till the third index(excluded).

s=”Python”
print (s[0:3])
#Output:Pyt

3. Slice indices have useful defaults; an omitted first index defaults to zero, an omitted second index defaults to the size of the string being sliced.

Omitted start index:

s[:4]-Returns element from the beginning of the string till the third index.

s="Python"
print (s[:4])
#Output:Pyth

Omitted stop index:

s[2:]-Returns element from the second index till the end of the string.

s="Python"
print (s[2:])
#Output:thon

4. Negative index.

s[-2:]-Returns element from second last index till the end of the string

s="Python"
print (s[-2:])
#Output:on

5.Using step-index.

s[1:5:2]-Returns element from index 1 till index 5(excluded) using step 2.

s="Python"
print (s[1:5:2])
#Output:yh
Image Source: Author

6.Out of range index.
Out of range indexes are handled gracefully when used for slicing.

s="Python"
print (s[10:])
#Output:''

Slicing List:

Slicing List returns a new list containing requested elements.

  1. Shallow copy.

n[:] -Returns shallow copy of the list.

n=[0,1,2,3,4,5]
print(n[:])
#Output:[0, 1, 2, 3, 4, 5]

Refer to my story for shallow copy.

2. n[1:3]-Returns new list containing elements from index 1 till index 3(excluded)

n=[0,1,2,3,4,5]
print(n[1:3])
#Output:[1, 2]

3.Omitted stop index

n[1:]-Returns a new list containing elements from the first index till the end of the list.

n=[0,1,2,3,4,5]
print(n[1:])
#Output:[1, 2, 3, 4, 5]

4. Omitted start index

n[:4]-Returns new list containing elements from the beginning of the list till the third index

n=[0,1,2,3,4,5]
print(n[:4])
#Output:[0, 1, 2, 3]

5. Slicing returns a new list but indexing returns the item only.

n[1:2]-Returns a new list containing an element from index 1.n

s[1]-Returns the element at index 1

n=[0,1,2,3,4,5]
print(n[1:2])
#Output:[1]
print (n[1])
#Output:1

6.Using step:

n[1:5:2]-Returns new list containing an element from index 1 till index 5(excluded) using step 2.

n=[0,1,2,3,4,5]
print(n[1:5:2])
#Output:[1,3]

Assignment to Slicing:

Assignment to slices is also possible, and this can even change the size of the list or clear it entirely.

  1. While assignment to slicing, no need to specify the same number of elements. We can assign any number of elements. This will even change the size of the list.
n=[0,1,2,3,4,5]
#Replace some values
n[1:3]=[999]
print (n)#Output:[0, 999, 3, 4, 5]

n[1:]=[22]
print (n)#Output:[0, 22]

2. We have to assign only iterable and not as a single element. It will raise TypeError.

n=[0,1,2,3,4,5]
#Replace some values
n[1:3]=99
#Output:TypeError: can only assign an iterable

3. We have to assign an iterable(list/tuple/string) to slicing.

n=[0,1,2,3,4,5]
#Assigning iterable to slicing
n[1:3]=[99]
print (n)
#Output:[0, 99, 3, 4, 5]

#tuple one element
n[1:3]=(77,)
print (n)
#Output:[0, 77, 4, 5]

n[1:3]='5'
print (n)
#Output:[0, '5', 5]

4.Removing/deleting elements by assignment to slicing.

n=[0,1,2,3,4,5]
n[1:4]=[]
print (n)#Output:[0, 4, 5]

5. Clearing the list by assigning the empty list to s[:]

n=[0,1,2,3,4,5]
n[:]=[]
print (n)#Output:[]

slice

An object usually containing a portion of a sequence.A slice is created using the subscript notation, [] with colons between numbers when several are given, such as in variable_name[1:3:5]. The bracket (subscript) notation uses slice objects internally.-Python documentation

slice constructor:

slice(start,stop,step)
slice(stop)

Return a slice object representing the set of indices specified by slice(start, stop, step). The start and step arguments default to None.

num=[0,1,2,3,4,5]
num1=slice(1,3)
print (num1)
#Output:slice(1, 3, None)
print (type(num1))
#Output:<class 'slice'>

Using the slice object in extending index syntax:

num=[0,1,2,3,4,5]
s=slice(1,3)
print (num[s])
#Output:[1, 2]

islice():

Makes an iterator that returns selected elements from the iterable. If the start is None, then iteration starts at zero. If the step is None, then the step defaults to one.If the stop is None, then iteration continues until the iterator is exhausted, if at all; otherwise, it stops at the specified position. islice() doesn’t support negative values for start, stop, and step.-Python documentation

itertools.islice(iterable,stop)
itertools.islice(iterable, start, stop[, step])

itertools.islice()

import itertools
#if only one argument is mentioned other than iterable,it is stop value.
num=itertools.islice([1,2,3,4,5,6,7,8,9,10],5)
print (list(num))#Output:[1, 2, 3, 4, 5]

#start=2 and stop=5 mentioned. It will start from second index and ends at fifth index
num=itertools.islice([1,2,3,4,5,6,7,8,9,10],2,5)
print (list(num))#Output:[3,4,5]

#start=2,step=3.It will start from second index and increment by 3.
num=itertools.islice([1,2,3,4,5,6,7,8,9,10],2,None,3)
print (list(num))#Output:[3,6,9]

#step is given as negative value,it raises ValueError
num=itertools.islice([1,2,3,4,5,6,7,8,9,10],2,None,-2)
print (list(num))#Output:ValueError: Step for islice() must be a positive integer or None.

Difference between Indexing and Slicing.

Image Source: Author

Conclusion

  • Item Assignment using indexing or Assignment using slicing for immutable objects like string, tuple, range will raise TypeError.
  • By using Extended Index syntax(Slicing), we can create a shallow copy of the list.
  • itertools.islice() -Returns an iterator that contains selected elements from the iterable.
    islice() doesn’t support negative values for start, stop, and step.

Resources(Python Documentation):

slice

itertools.islice

sequence

Indexing and Slicing

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google photo

You are commenting using your Google account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s