Khóa học algorithms

Array Slicing

0 phút đọc

To convert the provided HTML content to Markdown, you can use the following Markdown representation:

Array slicing involves taking a subset from an array and allocating a new array with those elements.

In Python 3.6 you can create a new list of the elements in my_list, from start_index to end_index (exclusive), like this:

python Copy
my_list[start_index:end_index]

You can also get everything from start_index onwards by just omitting end_index:

python Copy
my_list[start_index:]

Careful: there's a hidden time and space cost here! It's tempting to think of slicing as just "getting elements," but in reality you are:

  1. allocating a new list
  2. copying the elements from the original list to the new list

This takes

$$O(n)$$

time and

$$O(n)$$

space, where $$n$$ is the number of elements in the resulting list.

That's a bit easier to see when you save the result of the slice to a variable:

python Copy
tail_of_list = my_list[1:]

But a bit harder to see when you don't save the result of the slice to a variable:

python Copy
return my_list[1:]  # Whoops, I just spent O(n) time and space!

For item in slice:

python Copy
for item in my_list[1:]:
    pass  # Whoops, I just spent O(n) time and space!

So keep an eye out. Slice wisely.

Avatar
Được viết bởi

Admin Team

Gợi ý câu hỏi phỏng vấn

Không có dữ liệu

Không có dữ liệu

Gợi ý bài viết
Không có dữ liệu

Không có dữ liệu

Bình luận

Chưa có bình luận nào

Chưa có bình luận nào