Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is the difference between slicing in numpy arrays and slicing a list in Python?

Tags:

python

numpy

If curr_frames is a numpy array, what does the last line mean?

curr_frames = np.array(curr_frames)

idx = map(int,np.linspace(0,len(curr_frames)-1,80))

curr_frames = curr_frames[idx,:,:,:,]
like image 900
Mong Ting Wong Marma Avatar asked Jan 27 '19 15:01

Mong Ting Wong Marma


People also ask

What is slicing in NumPy array?

Slicing arrays Slicing in python means taking elements from one given index to another given index. We pass slice instead of index like this: [start:end] . We can also define the step, like this: [start:end:step] .

What is slicing in Python list?

In short, slicing is a flexible tool to build new lists out of an existing list. Python supports slice notation for any sequential data type like lists, strings, tuples, bytes, bytearrays, and ranges. Also, any new data structure can add its support as well.

What is the difference between slicing and indexing in Python?

“Indexing” means referring to an element of an iterable by its position within the iterable. “Slicing” means getting a subset of elements from an iterable based on their indices.

Can slicing done in an array in Python?

Python supports the slicing of arrays. It is the creation of a new sub-array from the given array on the basis of the user-defined starting and ending indices. We can slice arrays by either of the following ways. Array slicing can be easily done following the Python slicing method.


1 Answers

An important distinction from Python’s built-in lists to numpy arrays:

  • when slicing in the built-in list it creates a copy.

    X=[1,2,3,4,5,6]
    Y=X[:3]   #[1,2,3]
    

    by slicing X from 0-3 we have created a copy and stored it in the variable Y.

we can verify that by changing the Y and even if we change Y it does not effect X.

    Y[0]=20
    print(Y) # [20,2,3]
    print(X) # [1,2,3,4,5,6]
  • when slicing in numpy doesn't create a new copy but it still referring to original array

    A=np.array([1,2,3,4,5,6])
    B=A[:3]
    

By slicing A here and assigning it to B, still B referring to original array A.

We can verify that by changing an element in B and it will change the value in A as well.

    B[0]=20
    print(B) # [20,2,3]
    print(A) # [20,2,3,4,5,6]
like image 122
Ravi Avatar answered Oct 12 '22 23:10

Ravi