What will be the output of the following code?
```python
import numpy as np
arr = np.array([1, 2, 3, 4, 5])
print(arr[2])
```
Analysis & Theory
Arrays are zero-indexed, so arr[2] returns the third element, which is 3.
Given the following code, what does arr[1:4] return?
```python
import numpy as np
arr = np.array([10, 20, 30, 40, 50])
print(arr[1:4])
```
Analysis & Theory
The slice notation arr[1:4] returns the elements starting from index 1 (inclusive) up to index 4 (exclusive).
What will be the result of the following code?
```python
import numpy as np
arr = np.array([[1, 2, 3], [4, 5, 6]])
print(arr[1, 2])
```
Analysis & Theory
arr[1, 2] refers to the element in the second row (index 1) and third column (index 2), which is 6.
What does the following code do?
```python
import numpy as np
arr = np.array([1, 2, 3, 4, 5])
arr[::2]
```
A
A) Returns every element in the array
B
B) Returns every second element of the array
C
C) Returns the first and second elements
Analysis & Theory
The slice notation arr[::2] returns every second element starting from the first element, so the output will be [1, 3, 5].
What will arr[-1] return in the following code?
```python
import numpy as np
arr = np.array([10, 20, 30, 40, 50])
print(arr[-1])
```
Analysis & Theory
Negative indices in Python allow you to index from the end of the array. So arr[-1] returns the last element, which is 50.
What is the result of the following code?
```python
import numpy as np
arr = np.array([1, 2, 3, 4, 5])
print(arr[[1, 3]])
```
Analysis & Theory
The notation arr[[1, 3]] returns an array with the elements at indices 1 and 3, which are 2 and 4, respectively.
In the following code, what will arr[:, 1] return?
```python
import numpy as np
arr = np.array([[1, 2, 3], [4, 5, 6]])
print(arr[:, 1])
```
Analysis & Theory
The colon (:) selects all rows, while 1 selects the second column (index 1), so the output is [2, 5].
What will be the output of this code?
```python
import numpy as np
arr = np.array([1, 2, 3, 4, 5])
arr[1:3] = 10
print(arr)
```
Analysis & Theory
The slice arr[1:3] = 10 replaces the elements at indices 1 and 2 with 10, so the result is [1, 10, 10, 4, 5].
What will the following code output?
```python
import numpy as np
arr = np.array([1, 2, 3, 4, 5])
print(arr[::3])
```
Analysis & Theory
The slice arr[::3] selects every third element, starting from the first element. The output will be [1, 3, 5].
Which of the following is the correct syntax to access all elements of the second row in a 2D NumPy array?
```python
arr = np.array([[10, 20, 30], [40, 50, 60]])
```
Analysis & Theory
The colon (:) selects all columns, while 1 selects the second row (index 1). So arr[1, :] will return the second row: [40, 50, 60].