Research breakthrough possible @S-Logix pro@slogix.in

Office Address

Social List

How to do Indexing and Slicing in Python?

Indexing and Slicing in Python

Condition for Indexing and Slicing in Python

  • Indexing: Indexing in Python is a way to access individual elements of a sequence (like a string, list, or tuple) using their position.
  • Slicing: Slicing allows you to extract a subsequence from a sequence by specifying a start, stop, and step value.
Step-by-Step Process
  • Indexing:
    Use square brackets [] to access an element by its position in the sequence.
    Index starts at 0 for the first element, and -1 refers to the last element.
    Works with strings, lists, tuples, and other sequence types.
  • Slicing:
    Start: Index of the first element to include (default is 0).
    Stop: Index of the first element to exclude.
    Step: The interval between elements (default is 1).
Sample Code
  • # String indexing
    text = "Vignesh"
    print("Output for string index:")
    print(text[0])
    print(text[3])
    print(text[-1])
    print()
    # List indexing
    numbers_1 = [10, 20, "Kumar", 40, "Apple","Orange",100]
    print("Output for list index:")
    print(numbers_1[2])
    print(numbers_1[5])
    print(numbers_1[-3])
    print()
    # String slicing
    text = "Computer"
    print("Output for string slice:")
    print(text[1:4])
    print(text[:3])
    print(text[2:])
    print(text[::2])
    print()
    # List slicing
    numbers_2 = [10, 20, "Kumar", 40, "Apple","Orange",100]
    print("Output for list slice:")
    print(numbers_2[1:4])
    print(numbers_2[:3])
    print(numbers_2[::2])
Screenshots
  • Indexing and Slicing in Python1