What is slicing and indexing in Python explain with an example?

In Python, slicing and indexing are techniques used to access elements from a sequence, such as strings, lists, tuples, or other iterable objects. They allow you to extract specific portions of the sequence or retrieve individual elements at certain positions.

What is list indexing in Python with example?

Indexing is the process of accessing a single element from a sequence using its position, known as the index. In Python, indexing starts from 0 for the first element, 1 for the second element, and so on.

Example of indexing:

# Indexing a string
my_string = "Hello, World!"
print(my_string[0])  # Output: 'H'
print(my_string[7])  # Output: 'W'
print(my_string[-1])  # Output: '!'
Code language: PHP (php)

In the example above, we use square brackets [] to access individual characters from the string my_string. The index 0 retrieves the first character ‘H’, index 7 retrieves the eighth character ‘W’, and the negative index -1 accesses the last character ‘!’.

What is list slicing in Python with example?

Slicing enables you to extract a segment of a sequence by defining a range of indices. The slicing syntax follows the pattern: sequence[start:stop:step]. Here, ‘start’ represents the index of the first element to be included, ‘stop’ indicates the index of the first element to be excluded (i.e., the slice extends up to, but does not contain, this index), and ‘step’ denotes the number of elements to skip between each item in the slice (optional, with a default value of 1).

Example of slicing:

# Slicing a list
my_list = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
print(my_list[2:6])  # Output: [3, 4, 5, 6]
print(my_list[:5])  # Output: [1, 2, 3, 4, 5]
print(my_list[3:])  # Output: [4, 5, 6, 7, 8, 9, 10]
print(my_list[::2])  # Output: [1, 3, 5, 7, 9]
Code language: Python (python)

In this example, we slice the list my_list to retrieve specific portions of it. The first slice (my_list[2:6]) includes elements at indices 2, 3, 4, and 5, while the second slice (my_list[:5]) includes elements up to the index 4. The third slice (my_list[3:]) includes elements from index 3 to the end. The last slice (my_list[::2]) includes every second element starting from index 0.

Keep in mind that slicing and indexing work similarly for strings, tuples, and other sequences in Python.

Read More;

  • Yaryna Ostapchuk

    I am an enthusiastic learner and aspiring Python developer with expertise in Django and Flask. I pursued my education at Ivan Franko Lviv University, specializing in the Faculty of Physics. My skills encompass Python programming, backend development, and working with databases. I am well-versed in various computer software, including Ubuntu, Linux, MaximDL, LabView, C/C++, and Python, among others.

Leave a Comment