Programming & Scripting Tutorials

Python: More List Slicing



In a previous lesson we learned about slicing.
We can use the slicing that we learnt in the previous lesson to replace parts of a list.

To start off with lets create a list:

SeqOne = list('ItsRick')

We now have a list named SeqOne that contains ['I', 't', 's', 'R', 'i', 'c', 'k']; but what if we wanted to change this to "ItsFish"?
We could use slicing to replace "Rick" with "Fish" like so:

SeqOne[3:] = list('Fish')

All this does is gets element number four ('R') all the way to the end of the list (so that's all of "Rick") and replaces it with "Fish".
Our list is now: ['I', 't', 's', 'F', 'i', 's', 'h'].
We don't have to replace it with something that has the same number of characters though, for example we could do this:

SeqOne[3:] = list('Awesome')

The above would work completely fine.

We can also use slicing to add elements to our list, for example:

SeqOne[3:3] = list('Totally')

What this basically means is insert ['T', 'o', 't, 'a', 'l', 'l', 'y'] just before the element numbered 3 (which is 'A').

This Python tutorial was written by


Back to Python

Advertisement: