How to slice a Python list to get every third element

Published on Aug. 22, 2023, 12:15 p.m.

To slice a Python list to get every third element

To slice a Python list to get every third element, you can use the step parameter in a slice notation. Here’s an example:

my_list = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]

new_list = my_list[2::3]

print(new_list)

Output:

[3, 6, 9]

In this example, we have a list my_list with 10 elements. We use slice notation 2::3 to get every third element starting from the element at index 2 (which is the third element).

The general syntax for slice notation with a step parameter is:

list[start:end:step]

Where:

  • start: the starting index of the slice
  • end: the ending index of the slice (exclusive)
  • step: the step size of the slice

Omitting any of these parameters defaults them to their respective values: start=0, end=len(my_list), step=1.

To slice a numpy array every three elements

numpy

To slice a numpy array every three elements, you can use the same approach as with a regular Python list. Here’s an example:

import numpy as np

my_array = np.array([1, 2, 3, 4, 5, 6, 7, 8, 9, 10])

new_array = [my_array[i:i+3] for i in range(0, len(my_array), 3)]

print(new_array)

Output:

[array([1, 2, 3]), array([4, 5, 6]), array([7, 8, 9]), array([10])]

In this example, we first import the numpy library and create a numpy array my_array with 10 elements. We then use a list comprehension to create a new array new_array, splitting my_array into chunks of every three elements.

without using numpy

To slice a Python list every three elements without using numpy, you can use the same approach as with a numpy array. Here’s an example:

my_list = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]

new_list = [my_list[i:i+3] for i in range(0, len(my_list), 3)]

print(new_list)

Output:

[[1, 2, 3], [4, 5, 6], [7, 8, 9], [10]]

In this example, we first create a list my_list with 10 elements. We then use a list comprehension to create a new list new_list, splitting my_list into chunks of every three elements.

pandas

To slice a Pandas DataFrame to get every third row, you can use the same approach as with a Python list or numpy array. Here’s an example:

import pandas as pd

my_df = pd.DataFrame({'A': [1, 2, 3, 4, 5, 6], 'B': [7, 8, 9, 10, 11, 12]})

new_df = my_df.iloc[::3, :]

print(new_df)

Output:

   A   B
0  1   7
3  4  10

In this example, we first create a Pandas DataFrame my_df with 6 rows and 2 columns. We then use iloc to slice my_df and create a new DataFrame new_df that contains every third row.

The general syntax of the iloc method is:

df.iloc[start:stop:step, columns]

Where:

  • start: the starting index of the slice
  • stop: the ending index of the slice (exclusive)
  • step: the step size of the slice
  • columns: the columns to select

You can use : to select all columns. In this example, we used ::3 to select every third row and : to select all columns.

Tags: