---
# System prepended metadata

title: Lists 1

---

# Lists 1 - Introduction

---
title: Agenda
description:
duration: 300
card_type: cue_card
---

### Agenda

1. Motivation behind lists
2. How to initialize lists?
3. Indexing lists
4. Negative indexing
5. List methods
6. Membership Operator
7. Iterating over lists
8. Taking list as input

---
title: Motivation behind Lists
description:
duration: 600
card_type: cue_card
---

## Motivation behind Lists

* A Python function can have values. Those values have datatypes and can be stored in variables.
* Let's say we have to write a program that stores all the runs made by **Virat Kohli** in all International matches and find out the **minimum**, **maximum**, and **average**.
* Let's say the total number of matches Virat Kohli has played is 370.
* When we actually start writing a program for the problem above, we would have to define 370 variables. That is such a tedious task.
* Here is where **lists** come to our rescue.

<img src="https://d2beiqkhq929f0.cloudfront.net/public_assets/assets/000/040/053/original/SS1.png?1689621065" width=600 height=500>

---
title: Lists Introduction
description:
duration: 1500
card_type: cue_card
---

## Lists

* List is an **ordered** collection of data.
* It is a data structure that can store **multiple** values.
* List have no limit on how many values it can store.
* Creating a list -> `[]` squared brackets
* They store **comma separated** values.

Code:
``` python=
runs_virat = [67, 54, 12, 34, 77, 89, 101]

runs_virat
```

> **Output**
```
[67, 54, 12, 34, 77, 89, 101]
```

### How do I access a value from this list?
- Lists are accessed using indexes.

Code:
``` python=
runs_virat[0]
```

> **Output**
```
67
```

Code:
``` python=
runs_virat[1]
```

> **Output**
```
54
```

### How do I find out the count of total elements in a list?

- Using the `len()` function.

Code:
``` python=
len_runs_virat = len(runs_virat)

len_runs_virat
```

> **Output**
```
7
```

### How do I calculate the runs scored by Virat in last match?

Code:
``` python=
runs_virat[len(runs_virat) - 1]
```

> **Output**
```
101
```

Python makes it simpler by using **negative indexing**.

Code:
``` python=
runs_virat[-1]
```

> **Output**
```
101
```

#### What does `runs_virat[-len(runs_virat)]` give?

Code:
``` python=
runs_virat[-len(runs_virat)] # runs_virat[0]
```

> **Output**
```
67
```

<img src="https://d2beiqkhq929f0.cloudfront.net/public_assets/assets/000/040/054/original/SS2.png?1689621365" width=700 height=250>

### Question-1
Given the list `runs = [45, 67, 89, 12, 34, 56, 100]`, print the total runs on odd positions in the list.

**Motivation:** To explain the difference between positions and indexes.

Code:
``` python=
runs = [45, 67, 89, 12, 34, 56, 100]

print(runs[0] + runs[2] + runs[4] + runs[6])
```

> **Output**
```
268
```

---
title: List Methods
description:
duration: 1800
card_type: cue_card
---

## List Methods

<img src="https://d2beiqkhq929f0.cloudfront.net/public_assets/assets/000/040/055/original/SS3.png?1689621517" width=700 height=500>

### Can we add more elements to the list?

- Yes, using the `append()` method.

Code:
``` python=
# I want to add more runs to this.
runs = [45, 67, 89, 12, 34, 56, 100]

runs.append(71)

runs
```

> **Output**
```
[45, 67, 89, 12, 34, 56, 100, 71]
```

### Can I add an element at a particular index?

- Yes, using the `insert()` method.

Code:
``` python=
# I want to store an element at the zero-th index.
runs.insert(0, 25)

# Every value is moved ahead by 1-space.
runs
```

> **Output**
```
[25, 45, 67, 89, 12, 34, 56, 100, 71]
```

#### Let's say we have a variable `new_runs = [130, 69, 92]` and I want to add this to the end of the `runs` list.

- Adding multiple values at once can be done using the `extend()` method.

Code:
``` python=
new_runs = [130, 69, 92]

runs.extend(new_runs)

runs
```

> **Output**
```
[25, 45, 67, 89, 12, 34, 56, 100, 71, 130, 69, 92]
```

- We can also use "`+`" instead of extend().

Code:
``` python=
runs = runs + [200, 250, 300]

runs
```

> **Output**
```
[25, 45, 67, 89, 12, 34, 56, 100, 71, 130, 69, 92, 200, 250, 300]
```

#### `list.pop()` method
- removes element at a particular index.
- removes the last element if no index is passed.

Code:
``` python=
element = a.pop() # last element is removed
print(a)
```

> **Output**
```
[1, 2, 3, 4]
```

Code:
``` python=
element = a.pop(2) # element at second index is removed
print(a)
```

> **Output**
```
[1, 2, 4]
```

#### `list.remove()` method
- removes the first occurrence of a particular value from a list.

Code:
``` python=
a = [1, 2, 3, 4, 5, 4, 4, 4, 5]

a.remove(4) # first occourance is removed

print(a)
```

> **Output**
```
[1, 2, 3, 5, 4, 4, 4, 5]
```

#### `list.index()` method
- returns the index of an element corresponding to a particular value.
- if the list has multiple occurrence of that element, it will return the index of the first element that matches the value passed.

Code:
``` python=
a = [1, 2, 3, 4, 5]
a.index(3)
```

> **Output**
```
2
```

#### `list.count()` method
- returns the number of times a value passed appears inside a list.

Code:
``` python=
a = [1, 1, 1, 2, 2, 2, 5, 6, 1, 7, 3, 4]
a.count(7)
```

> **Output**
```
1
```

---
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: Membership Operator
description:
duration: 600
card_type: cue_card
---

## Membership Operator

### How can I check if an element exists in a list?

-  The `in` and `not in` are called **membership operators**, used to check whether a value exists in a sequence (such as a list, tuple, string, or set) or not.
  - `in` operator: This operator checks if a specified value exists in a list.
    - It returns True if the value is found in the list, and False otherwise.
  - `not in` operator: This operator checks if a specified value does not exist in a list. 
    - It returns True if the value is not found in the list, and False otherwise.

Code:
``` python=
my_list = [1, 2, 3, 4, 5]
print(3 in my_list)
print(6 in my_list)
```

> **Output**
```
True
False
```

Code:
``` python=
my_list = [1, 2, 3, 4, 5]
print(3 not in my_list)  
print(6 not in my_list)  
```

> **Output**
```
False
True
```
---
title: Iterating over Lists
description:
duration: 600
card_type: cue_card
---

## Iterating over Lists

- i -> `iterator` -> variable used to iterate
- range(5) -> `iterable` -> the collection of values on which we iterate
- print(i) -> `iteration block` -> body of the for loop

Code:
``` python=
for i in range(5):
    print(i)
```

> **Output**
```
0
1
2
3
4
```

#### Lists are also iterable.

Code:
``` python=
a = [56, 78, 89, 32, 101, 4]
for i in a:
    print(i)
```

> **Output**
```
56
78
89
32
101
4
```

---
title: Quiz-1
description: 
duration: 60
card_type: quiz_card
---

# Question

What will be the output of the following code?

``` python=
my_list = [1, 2, 3, 4, 5]
i = -1
while i >= -5:
    print(my_list[i], end=" ")
    i -= 1
```

# Choices
- [x] 5 4 3 2 1
- [ ] 1 2 3 4 5
- [ ] 5 3 1 2 4
- [ ] 5 4 3 1 2

---
title: Question - Sum, Average, Min and Max
description:
duration: 1200
card_type: cue_card
---

## Question-2

In runs_virat -> Calculate the sum, average, min and max

Code:
``` python=
runs_virat
```

> **Output**
```
[67, 54, 12, 34, 77, 89, 101]
```

**Initializing Variables**
``` python=
length_runs = 0
average_runs = 0
sum_runs = 0
max_runs = 0
min_runs = 0
```

**Looping over `runs_virat` list**
``` python=
for i in runs_virat:
    sum_runs = sum_runs + i
    length_runs = length_runs + 1
```

**Length of the list -**
``` python=
length_runs
```
> **Output**
```
7
```

**Total runs scored -**
``` python=
sum_runs
```
> **Output**
```
434
```

**Calculating the average runs scored -**
``` python=
average_runs = sum_runs / length_runs
average_runs
```
> **Output**
```
62.0
```

**Calculating the minimum runs scored -**
``` python=
min_runs = a[0]

for i in a:
    if i < min_runs:
        min_runs = i
min_runs
```
> **Output**
```
4
```

**Calculating the maximum runs scored -**
``` python=
max_runs = a[0]

for i in a:
    if i > max_runs:
        max_runs = i

max_runs
```
> **Output**
```
101
```

#### We can also use the in-built python functions.

Code:
``` python=
sum_runs = sum(runs_virat)
sum_runs
```
> **Output**
```
434
```

Code:
``` python
average_runs = sum_runs / len(runs_virat)
average_runs
```
> **Output**
```
62.0
```


Code:
``` python
min(runs_virat)
```
> **Output**
```
12
```

Code:
``` python=
max(runs_virat)
```
> **Output**
```
101
```

---
title: Quiz-2
description: 
duration: 60
card_type: quiz_card
---

# Question

What is the output of the following code?

``` python=
my_list = ["apple", "banana", "orange"]
for i in range(len(my_list)):
    print(my_list[i] + " is a fruit.", end=" ")
```

# Choices
- [ ] fruit. fruit. fruit.
- [ ] apple banana orange
- [ ] is a fruit. is a fruit. is a fruit.
- [x] apple is a fruit. banana is a fruit. orange is a fruit.

---
title: Question - Matches with Even Index
description:
duration: 600
card_type: cue_card
---

## Question-3

Calculate the sum of runs made by Virat Kohli in all matches with **even index**.

Code:
``` python=
# This will give us all the indices.
for i in range(len(runs_virat)):
    print(i)
```

> **Output**
```
0
1
2
3
4
5
6
```

Code:
``` python=
sum_even_runs = 0
for i in range(len(runs_virat)):
    if i % 2 == 0:
        sum_even_runs = sum_even_runs + runs_virat[i]
sum_even_runs
```

> **Output**
```
257
```

---
title: Quiz-3
description: 
duration: 60
card_type: quiz_card
---

# Question

What is the output of the following code?

``` python=
my_list = [10, 20, 30, 40, 50]
i = 0
while i < len(my_list):
    my_list[i] *= 2
    i += 1
print(my_list)
```

# Choices
- [ ] [10, 20, 30, 40, 50]
- [ ] [1, 2, 3, 4, 5]
- [x] [20, 40, 60, 80, 100]
- [ ] [5, 10, 15, 20, 25]

---
title: Taking list as input
description:
duration: 900
card_type: cue_card
---

### How do I take a list as input?

- **Getting the number of elements**: We first prompt the user to enter the number of elements they want to input into the list.

- **Initializing an empty list**: We create an empty list (my_list) that will hold the elements entered by the user.

- **Using a for loop**: We use a for loop to iterate over a range of numbers starting from 0 to num_elements - 1.

- **Getting input for each element**: Inside the loop, we prompt the user to enter each element one by one. The `input()` function is used to take user input, and the entered element is appended to the list using the `append()` method.

Code:
```python=
# Taking input for a list using a for loop

# Step 1: Get the number of elements in the list from the user
num_elements = int(input("Enter the number of elements in the list: "))

# Step 2: Initialize an empty list to store the elements
my_list = []

# Step 3: Use a for loop to iterate over the specified number of elements
for i in range(num_elements):
    # Step 3a: Get input for each element and append it to the list
    element = input(f"Enter element {i+1}: ")
    my_list.append(element)

# Step 4: Print the list
print("The list you entered is:", my_list)
```

---
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/22192/
