Python Indexing

tags: #python/intro

What is indexing?

In Python, indexing refers to the process of accessing a specific element in a sequence, such as a string or list, using its position or index number[1].

Zero-Indexing

Indexing in Python starts at 0, which means that the first element in a sequence has an index of 0, the second element has an index of 1, and so on. Note that index positions are named from right to left.

If the iterable object,s, has n items, the last item is s[n-1].

We can index through a sequence by specifying the index number of the desired item in an iterable object (sequence) using the index operator ( [] ) to enclose the index number.

The index number must be an integer and starts at zero; therefore, the nth character is at index n-1.

Positive Indexing vs Negative Indexing

There are two indexing system in Python:

  1. Positive Indexing: i.e. 0 indexing, where the first element starts with 0

  2. Negative Indexing: where we count backwards, such that first element at the end of list starts with 1. This is useful in selecting elements at the end of the list.

Pasted image 20231230213829.png500

What happens if the n value is beyond the length? IndexError

An IndexError can occur when we use an index number that is outside the range of the sequeence.

Example of indexing a Python List:

Pasted image 20231230214010.png500


Python Slicing

Python slicing is used to return a segment of a sequence or iterable object. This allows you to create a new sequence that consists a subset of the original elements.

Return Object

Note that a slice will always return a list object.

Basic Syntax

sequence[start:stop:step]

Examples:

# Slicing a List
my_list = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
subset = my_list[2:7]  # Get elements from index 2 to 6 (exclusive)
print(subset)  # Output: [2, 3, 4, 5, 6]



# Slicing a String
my_string = "Hello, World!"
substring = my_string[7:12]  # Get characters from index 7 to 11 (exclusive)
print(substring)  # Output: World



# Slicing with a Step
my_list = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
subset = my_list[1:9:2]  # Get elements from index 1 to 8 (exclusive) with a step of 2
print(subset)  # Output: [1, 3, 5, 7]e

Other Slicing Methods

Selecting all elements in a list
a[:]
Selecting the first n elements
a[:n]
Selecting the last n elements
a[-n:]
When you want to select all elements after the slide including the last
a[n:]

  1. https://www.datacamp.com/tutorial/python-list-index ↩︎

Powered by Forestry.md