Array slicing gets a subset of an array

WBOY
Release: 2024-04-29 18:15:02
Original
338 people have browsed it

Array slicing is a simple way to obtain a subset of an array. The syntax is array[start:stop:step]. By specifying the index range and step size, you can get the required elements. For example, array[2:6] gets elements from index 2 to 6 (exclusive), array[::-1] reverses the array.

Array slicing gets a subset of an array

Array slicing: Obtaining a subset of an array

Array slicing is a convenient way to obtain a subset of an array in Python . It allows you to specify elements to include or exclude from an array using a concise syntax.

Syntax

Array slicing uses square brackets ([]), followed by a colon (:) to separate index ranges:

array[start:stop:step]
Copy after login
  • start: Specifies the index at which the slice starts (inclusive).
  • stop: Specifies the index at which the slice ends (not included).
  • step: Specify the slicing step (optional). It specifies how many elements to skip.

Practical case

The following example demonstrates how to use array slicing to obtain a subset of an array:

# 创建一个数组
array = [1, 2, 3, 4, 5, 6, 7, 8, 9]

# 获取数组的前 4 个元素
sub_array1 = array[:4]
print(sub_array1)  # 输出:[1, 2, 3, 4]

# 获取数组中索引 2 到 6(不包含)的元素
sub_array2 = array[2:6]
print(sub_array2)  # 输出:[3, 4, 5, 6]

# 获取以步长 2 递增的数组元素
sub_array3 = array[::2]  # 等同于 array[0:len(array):2]
print(sub_array3)  # 输出:[1, 3, 5, 7, 9]

# 反转数组
sub_array4 = array[::-1]
print(sub_array4)  # 输出:[9, 8, 7, 6, 5, 4, 3, 2, 1]
Copy after login

Some points to note

  • Indices start from 0.
  • If start or stop are omitted, it will be interpreted as the beginning or end of the array.
  • step Default is 1.
  • If start is greater than stop, the slice will be empty.
  • Slicing returns a new array, which is independent of the original array.

The above is the detailed content of Array slicing gets a subset of an array. For more information, please follow other related articles on the PHP Chinese website!

Related labels:
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template