INDEXING

In Python, indexing is used to access individual elements of sequences such as strings, lists, or tuples. Python supports both positive and negative indexing. Positive indexing starts from 0 at the first element and increases by 1 for each subsequent element. Negative indexing starts from -1 at the last element and decreases by -1 toward the beginning, allowing convenient access to elements from the end of a sequence. For example, in the string s = "Codechef", s[0] returns 'C', while s[-1] returns 'f'. This negative indexing is a built-in, safe feature in Python. In contrast, C and C++ do not natively support negative indexing. Attempting to use a negative index like s[-1] in C or C++ will not access the last element, but instead points to memory before the start of the array, resulting in undefined behavior. Therefore, negative indexing in C or C++ should be avoided, and elements should only be accessed using non-negative indices within the valid array bounds.

#!/usr/bin/env python3

def main() -> None:
    word = "Programming";
    print(word[2]);
    print(word[1]);

if __name__ == "__main__":
    main();
    
 * OUTPUT
    o
    r

Last updated