1 of 19

COL100 �Introduction to Computer Science

Lecture 15 – Lists

February, 2025

Semester II

2024-2025

Vireshwar Kumar, Aaditeshwar Seth

CSE@IITD

2 of 19

Agenda

  • Lists

2

Disclaimer: The contents of these slides are taken from various publicly available resources such as books, talks and lectures. They are being used for the purpose of classroom teaching and academic dissemination only. The sources are acknowledged wherever possible.

3 of 19

Structured Data Types

  • Lists
    • nums = [1,2,3,4]
    • Refer to individual elements as: nums[0], nums[1], nums[2]…

​

  • Strings
    • fruit = ‘banana’
    • Refer to individual elements as: fruit[0], fruit[1], fruit[3]…

3

4 of 19

List

  • Ordered sequence of information, accessible by index

​

  • A list is denoted by square brackets []

​

  • A list contains elements

​

  • Usually homogeneous (i.e., all integers)

​

  • Can contain mixed types

​

  • List elements can be changed so a list is mutable

​

4

5 of 19

Indices and Ordering

  • Indexing starts from 0

myList = [5, 6, 9, 0, 1]

myData = myList[2]

print(myData) # 9

5

6 of 19

Changing Elements

  • Lists are mutable.

​

myList = [5, 6, 9, 0, 1]

myList[3] = 2

print(myList) # [5, 6, 9, 2, 1]

6

7 of 19

Appending Elements

  • New elements can be added at the end of the list.

myList = [5, 6, 9]

myList.append(7)

print(myList) # [5, 6, 9, 7]

​

​

7

8 of 19

Extending List

  • New list can be added at the end of the list.

myList = [5, 6, 9]

myList.extend([0,6])

print(myList) # [5, 6, 9, 0, 6]

----------------

myList = [5, 6, 9]

myOtherList = [0, 6]

myList.extend(myOtherList)

print(myList) # [5, 6, 9, 0, 6]

----------------

myList = [5, 6, 9]

myOtherList = [0, 6]

myOtherList.extend(myList)

print(myOtherList) # [0, 6, 5, 6, 9]

8

9 of 19

Concatenate Two Lists

  • + operator can be used to concatenate two lists together.

​

​

myList1 = [2,1,3]

myList2 = [4,5,6]

combinedList = myList1 + myList2

print(combinedList)

#[2,1,3,4,5,6]

9

10 of 19

Remove Elements

  • Delete element at a specific index with del(L[index])

​

  • Remove element at end of list with L.pop(), returns the removed element

​

  • Remove a specific element with L.remove(element)
    • Looks for the element and removes it
    • If element occurs multiple times, removes first occurrence

myList = [5, 6, 9, 1, 3, 5]

del(myList[2])

print(myList) # [5, 6, 1, 3, 5]

​

myList = [5, 6, 9, 1, 3, 5]

lastNum = myList.pop()

print(myList) # [5, 6, 9, 1, 3]

​

myList = [5, 6, 9, 1, 3, 5]

myList.remove(9)

print(myList) # [5, 6, 1, 3, 5]

​

10

11 of 19

Managing lists

names = ["aadi", "viresh", "amit", "riju", "maya", "tarun"]

marks_col100 = [100, 100, 80, 90, 75, 95]

marks_col106 = [50, 70, 100, 100, 80, 95]

marks_col334 = [93, 86, 63, 74, 76, 75]

marks_avg = [0] * 6

​

max_marks = -1

max_marks_index = -1

for i in range(0, 6):

marks_avg[i] = (marks_col100[i] + marks_col106[i] + marks_col334[i]) / 3

if marks_avg[i] > max_marks:

max_marks = marks_avg[i]

max_marks_index = i

​

print(marks_avg)

print("max marks:", max_marks, "awarded to", names[max_marks_index])

​

#reversing a list

new_names = [""] * len(names)

for i in range(0, len(names)):

new_names[i] = names[len(names) - 1 - i]

​

print(new_names)

print("max marks:", max_marks, "awarded to", new_names[max_marks_index])

11

12 of 19

Factorial Sequence List

def factorialList(n):

if(n == 0):

return [0]

elif(n == 1):

return [0, 1]

else:

fact = [0, 1]

count = 2

while (count < n + 1):

fact.append(fact[count-1] * count)

count = count + 1

return fact

​

fact_list = factorialList(10)

print(fact_list)

12

13 of 19

Factorial Sequence List

def fact(n):

if n == 0:

return 0

elif n == 1:

return 1

else:

val = 1

for i in range(2, n + 1):

val = val * i

return val

​

#list comprehension

fact_list = [fact(x) for x in range(0, 11)]

print(fact_list)

13

Why is this not very efficient?

14 of 19

Fibonacci Sequence List

def fibonacciList(n):

if(n == 0):

return [0]

elif(n == 1):

return [0, 1]

else:

fib = [0, 1]

count = 2

while (count < n + 1):

fib.append(fib[count-2] + fib[count-1])

count = count + 1

return fib

​

fib_list = fibonacciList(10)

print(fib_list)

14

15 of 19

Iteration through List: Linear Search

numFind = 5

myList = [2, 5, 6, 1, 9, 5]

found = False

for count in range(0,len(myList)):

if(numFind == myList[count]):

found = True

print("Found at index: ", count)

break

if (not(found)):

print("Not found")

15

16 of 19

Build a list of prime numbers

#https://projecteuler.net/problem=7

def isprime(num, primes):

maxlim = math.sqrt(num)

for i in primes:

if num % i == 0:

return False

if i > maxlim:

break

return True

​

primes = [3]

num = 5

while len(primes) < 10001:

if isprime(num, primes):

primes.append(num)

num += 2

​

print(primes[9999]) #2 is the first prime, but not in the list

16

17 of 19

Plot a histogram, create CSVs

with open("numlist.csv", "r") as infile:

n = int(infile.readline())

nums = [0] * n

for i in range(0, n):

nums[i] = int(infile.readline())

print(n, nums)

​

counts = [0] * 10

for num in nums:

counts[num // 10] += 1

print(counts)

​

with open("numhist.csv", "w") as outfile:

for i, count in enumerate(counts):

outfile.write(str(i * 10) + "," + str(count) + "\n")

​

plt.bar([i * 10 for i in range(0, 10)], counts)

plt.show()

17

18 of 19

Useful tools for list creation

    • Initializing a list with the same value for each element

mylist = [0] * 10

​

    • Initializing a list with a value from a function

mylist = [x*x for x in range(0, 10)]

mylist = (list)(map(lambda x: x*x, range(0, 8)))

​

    • Modify with numpy

import numpy as np

mylist = [x*x for x in np.arange(0, 10, 0.5)]

18

19 of 19

Additional examples

  • Calculate the average in a list of numbers, max in a list of numbers
  • Binary search
  • Vector multiplication of two lists, with and without using map
  • Reverse a list with and without list splicing
  • Build a list of prime numbers
  • Find prime factors of a number
  • https://projecteuler.net/problem=3
    • What is the largest prime factor of the number 600851475143?
  • Plot a histogram for a list of numbers

19