# Lists 2 - Slicing and 2D
---
title: Agenda
description:
duration: 300
card_type: cue_card
---
### Agenda
1. List Slicing
1. Motivation behind list slicing.
2. List slicing with positive & negative indices
3. List slicing with positive & negative step sizes
2. 2D Lists
1. Introduction to 2D lists
2. Indexing in 2D lists
3. Iterating over 2D lists
---
title: List Slicing
description:
duration: 1800
card_type: cue_card
---
## Motivation behind List Slicing
The following questions will emphasize the need for list slicing.
### **Question-1**
Given a list of all runs by Virat Kohli, create a new list of runs made in last 5 matches.
`runs = [62, 85, 74, 10, 12, 101, 122, 99, 81, 55]`
Code:
``` python=
runs = [62, 85, 74, 10, 12, 101, 122, 99, 81, 55]
result = []
for i in range(1, 6):
result.append(runs[-i])
result
```
> **Output**
```
[55, 81, 99, 122, 101]
```
### **Question-2**
Given a list of all runs by Virat Kohli, create a new list of runs made in odd matches (even indices).
`runs = [62, 85, 74, 10, 12, 101, 122, 99, 81, 55]`
Code:
``` python=
def odd_runs(runs):
result = []
for i in range(len(runs)):
if i % 2 == 0:
result.append(runs[i])
return result
runs = [62, 85, 74, 10, 12, 101, 122, 99, 81, 55]
odd_runs(runs)
```
> **Output**
```
[62, 74, 12, 122, 81]
```
#### The questions **discussed above** were to show learners the importance and need of list slicing.
### **Accessing an element from a list -**
* We can access an element using index number.
* The index number must be within the range of the length of the list.
<img src="https://d2beiqkhq929f0.cloudfront.net/public_assets/assets/000/040/056/original/SS1.png?1689623847" width=600 height=250>
### **Acessing a range of elements -**
* We can access a range of elements using list slicing.
* The original list is not updated when slicing.
* The syntax is as follows :
<img src="https://d2beiqkhq929f0.cloudfront.net/public_assets/assets/000/040/057/original/SS2.png?1689623899" width=600 height=250>
### **Accessing odd numbered elements -**
* We can use the step size to skip certain elements.
* By default, the step size is 1.
* The syntax is as follows :
<img src="https://d2beiqkhq929f0.cloudfront.net/public_assets/assets/000/040/058/original/SS3.png?1689623949" width=600 height=250>
\
**Note:**
* If we just provide the start value and not the end value, something like ```runs[5:]```, it will print all the elements from index 5 till the end of the list.
* If we just provide the end value and not the start value, something like ```runs[:5]```, it will print all the elements til index 5 excluding the index 5.
* If we do not provide the start and the end value, but we do provide a value in the step size, something like ```runs[::2]```, it will print all the elements at even indexes in the list.
Code:
``` python=
print(runs[5:])
print(runs[:5])
print(runs[::2])
```
> **Output**
```
[101, 122, 99, 81, 55]
[62, 85, 74, 10, 12]
[62, 74, 12, 122, 81]
```
---
title: Negative List Slicing
description:
duration: 1800
card_type: cue_card
---
## Negative List Slicing
<img src="https://d2beiqkhq929f0.cloudfront.net/public_assets/assets/000/040/060/original/SS4.png?1689624149" width=600 height=175>
#### We can use a step size of -1, to back traverse a list.
Code:
``` python=
runs[5:0:-1]
```
> **Output**
```
[101, 12, 10, 74, 85]
```
#### We can go from the second last element to the 5th last, with a jump of -1.
Code:
``` python=
runs[-2:-5:-1]
```
> **Output**
```
[81, 99, 122]
```
#### If we do not provide the end end value -
Code:
``` python=
runs[-2::-1]
```
> **Output**
```
[81, 99, 122, 101, 12, 10, 74, 85, 62]
```
- Default end value = `len(a)` $\rightarrow$ step size = +1
- Default end value = covering the first element $\rightarrow$ step size = -1
### Conclusion
- Right to Left in a list $\Rightarrow$ Negative jump.
- Left to Right in a list $\Rightarrow$ Positive jump.
<img src="https://d2beiqkhq929f0.cloudfront.net/public_assets/assets/000/040/065/original/SS8.png?1689624739" width=600 height=350>
### **Question-3**
Given a python list `a = [10, 20, 30, 440, 50, 60, 70, 80, 90, 100]`
What will be the output of the followings?
1. ```a[3:5]```
1. ```a[:]```
1. ```a[-2:-5:-1]```
1. ```a[-2:-7]```
1. ```a[-2:]```
1. ```a[-8:5:-1]```
Code:
```python=
a = [10, 20, 30, 440, 50, 60, 70, 80, 90, 100]
print(a[3:5])
print(a[:])
print(a[-2:-5:-1])
print(a[-2:-7])
print(a[-2:])
print(a[-8:5:-1])
```
> **Output**
[440, 50]
[10, 20, 30, 440, 50, 60, 70, 80, 90, 100]
[90, 80, 70]
[]
[90, 100]
[]
### **Question-4**
Rotate a list by 1 element (last element should be removed and added to the start).
`[1, 2, 3, 4, 5]` $\Rightarrow$ `[5, 1, 2, 3, 4]`
Code:
``` python=
a = [1, 2, 3, 4, 5]
last_element = a[-1]
initial_elements = a[:len(a)-1]
result = [last_element] + initial_elements
print(result)
```
> **Output**
```
[5, 1, 2, 3, 4]
```
---
title: Break & Doubt Resolution
description:
duration: 600
card_type: cue_card
---
### Break & Doubt Resolution
`Instructor Note:`
* Kindly take this time (up to 5-10 mins) to give a short break to the learners.
* Meanwhile, you ask them to share their doubts (if any) regarding the topics covered so far.
---
title: List Reversal
description:
duration: 900
card_type: cue_card
---
### **Question-6**
Write a program to reverse a list.
#### 1. Use `a.reverse()` - reverses the original list
Code:
``` python=
a = [1, 2, 3, 4, 5]
a.reverse()
print(a)
```
> **Output**
```
[5, 4, 3, 2, 1]
```
#### 2. Use `list slicing` - reverses the list by creating a copy
Code:
``` python=
a = [1, 2, 3, 4, 5]
a_reversed = a[::-1]
print(a_reversed)
```
> **Output**
```
[5, 4, 3, 2, 1]
```
#### 3. Use `reversed()` function
Code:
``` python=
a = [1, 2, 3, 4, 5]
a_reversed = list(reversed(a))
print(a_reversed)
```
> **Output**
```
[5, 4, 3, 2, 1]
```
---
title: 2D Lists
description:
duration: 900
card_type: cue_card
---
## 2D Lists
* Lists are heterogenous, which means they can store elements of any type.
* This means a list can also store a list within it.
* These type of lists are called nested lists.
<img src="https://d2beiqkhq929f0.cloudfront.net/public_assets/assets/000/040/137/original/SS1.png?1689711252" width=600 height=300>
* We can also create lists only containing lists within them.
<img src="https://d2beiqkhq929f0.cloudfront.net/public_assets/assets/000/040/140/original/SS2.png?1689711295" width=600 height=400>
* A nested list can be imagined as a `matrix` with rows and columns.
<img src="https://d2beiqkhq929f0.cloudfront.net/public_assets/assets/000/040/141/original/SS3.png?1689711340" width=600 height=350>
\
Code:
``` python=
a = [[1, 2, 3], [4, 5, 6], [7, 8, 9]]
print(a)
```
> **Output**
```
[[1, 2, 3], [4, 5, 6], [7, 8, 9]]
```
---
title: Indexing in 2D Lists
description:
duration: 900
card_type: cue_card
---
### Indexing in 2D Lists
<img src="https://d2beiqkhq929f0.cloudfront.net/public_assets/assets/000/040/142/original/SS4.png?1689711443" width=600 height=500>
How do I access "3" from `a`?
- We go in the `3rd element` of the `0th row`.
Code:
``` python=
a = [[1, 2, 3], [4, 5, 6], [7, 8, 9]]
print(a[0][2])
```
> **Output**
```
3
```
---
title: Iterating over 2D Lists
description:
duration: 900
card_type: cue_card
---
### Iterating over 2D Lists
Whenever we are iterating over a 2D list, we need to know how many rows & columns there are in the nested list.
Code:
``` python=
a = [[1, 2, 3], [4, 5, 6], [7, 8, 9]]
rows = len(a)
columns = len(a[0])
```
``` python=
# Iterating over the 2D list
for i in range(rows):
for j in range(columns):
print(a[i][j], end = " ")
print()
```
> **Output**
```
1 2 3
4 5 6
7 8 9
```
Code:
``` python=
random = [[1, 2, 3], ["a", "b", "c", "d", "e"], [4.5, 6.7]]
for i in random:
for j in i:
print(j, end = " ")
print()
```
> **Output**
```
1 2 3
a b c d e
4.5 6.7
```
---
title: Matrix-based Question
description:
duration: 900
card_type: cue_card
---
## **Question-6**
Take a `3X3` matrix as an input from the user.
Given this matrix -
1. Calculate the sum of all the elements in the matrix.
2. Calculate the sum of elements in each row.
Code:
``` python=
a = [ ]
for i in range(3):
inner_list = []
for j in range(3):
inner_list.append(int(input()))
a.append(inner_list)
```
> **Input**
```
1
2
3
4
5
6
7
8
9
```
**1. Sum of all elements -**
Code:
``` python=
sum_all = 0
for i in a:
for j in i:
sum_all = sum_all + j
print(sum_all)
```
> **Output**
```
45
```
**2. Sum of each row -**
Code:
``` python=
sum_rows = [0 , 0, 0]
rows = len(a)
cols = len(a[0])
for i in range(rows):
for j in range(cols):
sum_rows[i] = sum_rows[i] + a[i][j]
sum_rows
```
> **Output**
```
[6, 15, 24]
```
---
title: Practice Coding Question(s)
description:
duration: 600
card_type: cue_card
---
### Practice Coding Question(s)
You can pick the following question and solve it during the lecture itself.
This will help the learners to get familiar with the problem solving process and motivate them to solve the assignments.
<span style="background-color: pink;">Make sure to start the doubt session before you start solving the question.</span>
Q. https://www.scaler.com/hire/test/problem/22194/