5

INDEXING, SLICING & DICING

by

The Education Machine

[support@theeducationmachine.com]

Indexing

This is used to find out the value at some index/location within a string.
This is done by giving index location in the square brackets [ ] as suffix of variable name.
Indexing can be performed for Strings, Tuples, Lists, Sets & Dictionaries but NOT for numbers.


reserved_keywords

While indexing from left to right, the count always start from 0. And from right to left, the count starts from -1.
(as shown in the above picture)


In below code, 'h' is located in the string at index 1.

  name = 'The Education Machine'
  name[1]


Output:
'h'

In following cell, 'a' is located in the string at index -6.

  name = 'The Education Machine'
  name[-6]


Output:
'a'

Slicing and Dicing

Slicing and dicing is to cut the data into smaller chunks.
It is very similar to SUBSTR or SUBSTRING function in SQL.
User have to specify the start position, end position and step value(optional), each separated by ":"
Also,python skips the character/element located at end position.


In below cell, the user is taking out a small part of the string with the help of slicing and dicing.
Here, 1 is the start position and 6 is the end position. And it has skipped the character at end position i.e. 'u'.

  name = 'The Education Machine'
  name[1:6]


Output:
'he Ed'

Guess the output of below codes and verify your answers.

   name[9:11]


'ti'


  name[1:-5]


'he Education Ma'


  name[:4]


'The '


  name[4:-3:1]


'Education Mach'


  name[4:-3:2]


'EuainMc'


  name[4:-13:-1]


' '


  name[::]


'The Education Machine'


  name[::-1]


'enihcaM noitacudE ehT'


Reverse the name using input() function.

  name = input("Enter your name: ")
  print(f"Thanks for entering your name!
  Your reversed name is: {name[::-1]}")


Output:
Enter your name: The Education Machine
Thanks for entering your name!
Your reversed name is: enihcaM noitacudE ehT