PythonPython Data TypesIndexing in Sequencial Data Types

Indexing in Python

In sequence data types like strings, lists, and tuples, each element is assigned a unique position called an index. Indexing allows you to access individual elements from a sequence. Python supports two types of indexing:

  1. Forward Indexing: Starts from 0 for the first element and increments by 1 for each subsequent element.
  2. Backward Indexing: Starts from -1 for the last element and decrements by 1 for each previous element.

Indexing in Python

Accessing Characters in a String

string1 = "PYTHONFORALL"
# Accessing elements using forward indexing
print(string1[4])   # Output: O
 
# Accessing elements using backward indexing
print(string1[-4])  # Output: R

Accessing Elements in a List

list1 = [15, 20, 4.5, 'H']
 
# Accessing elements using forward indexing
print(list1[0])   # Output: 15
 
# Accessing elements using backward indexing
print(list1[-1])  # Output: H