Negative Indexing in Python

What is the output of this code snippet?

 

x = 'cool'
print(x[-1] + x[-2]
      + x[-4] + x[-3])

You can index single characters in strings using the bracket notation. The first character has index 0, the second index 1, and so on. Did you ever want to access the last element in the string? Counting the indices can be a real pain for long strings with more than 8-10 characters.
But no worries, Python has a language feature for this.
Instead of start counting from the left, you can also start from the right. Access the last character with the negative index -1, the second last with the index -2, and so on.
In summary, there are two ways to index sequence positions, from the left and from the right.

 


Are you a master coder?
Test your skills now!

 

Related Video

Solution

loco

 

Leave a Comment

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