Lists in Python

Introduction to Collections

  • Collections are essential for tracking related values.
  • Examples of collections include:
    • Grades for a class
    • Names of employees
  • Prior methods involved using sentinel values and loops with no long-term storage options.
  • Collections enable the storage of many related values under a single variable name.

Indexing a Collection

  • A collection is a data type that permits the storing of multiple values.
  • Indexing is essential for accessing individual elements within a collection.
    • Numeric indexing starts from 0:
    • Index 0: first item
    • Index 1: second item
    • Index 2: third item, etc.
  • Avoids the need for multiple variable names (e.g., grade1, grade2).
  • Instead of naming each value, individual elements can be accessed via the collection name and index:
    • Example: grades[0], grades[1], grades[2], etc.

Introduction to Lists

  • Lists are ordered sequences that store multiple values within a single collection.
  • Creation of lists is achieved by enclosing values in square brackets, separating them with commas:
    • Example:
    • [1,2,3,4,5][1, 2, 3, 4, 5]
    • ["Hello","This","is","a","list","of","strings"]["Hello", "This", "is", "a", "list", "of", "strings"]
    • [][] (an empty list)
  • Lists can contain any data type and can include mixed data types:
    • Example: ["Hello",1,2,3.7,["alist","insidealist"]]["Hello", 1, 2, 3.7, ["a list", "inside a list"]]
  • Declaring a variable of list type:
    • Example: Mylist=[37,42,64,12,37]Mylist = [37, 42, 64, 12, 37]

Accessing Values in a List

  • To access or modify a value within a list, use the syntax:
    • listName[index]listName[index]
  • Indexing conventions:
    • Starts at 0 and ends at (number of items - 1).
  • Access examples:
    • Mylist=[42,37,64,12,37]Mylist = [42, 37, 64, 12, 37]
    • Lastextvalue=Mylist[4]<br/>ightarrow37Last ext{ }value = Mylist[4] <br /> ightarrow 37
    • Firstextvalue=Mylist[0]<br/>ightarrow42First ext{ }value = Mylist[0] <br /> ightarrow 42
  • Using variables for indexing:
    • Example:
    • i=2i = 2
    • val=Mylist[i]<br/>ightarrow64val = Mylist[i] <br /> ightarrow 64
    • val=Mylist[i+1]<br/>ightarrow12val = Mylist[i+1] <br /> ightarrow 12
  • Modifying values in a list:
    • Example:
    • Mylist[3]=17<br/>ightarrowMylist=[42,37,64,17,37]Mylist[3] = 17 <br /> ightarrow Mylist = [42, 37, 64, 17, 37]

Handling Out of Bounds Values

  • When accessing an element in a list, ensure the index is within valid bounds.
    • Example List: Mylist=[42,37,64,12,37]Mylist = [42, 37, 64, 12, 37]
  • Valid indices range from 0 to 4 in this scenario (5 items total).
  • Attempting to access an out of bounds index:
    • Example:
    • Mylist[6]Mylist[6] → ERROR: index out of bounds
  • Utilize the built-in len()len() function to determine list size:
    • Example:
    • print(Mylist[len(Mylist)1])print(Mylist[len(Mylist) - 1])

Printing a List

  • The print function can display entire lists in square brackets.
    • Example:
    • Mylist=[42,37,64,12,37]Mylist = [42, 37, 64, 12, 37]
    • print(Mylist)print(Mylist) → Output: [42,37,64,12,37][42, 37, 64, 12, 37]
  • Printing a single value using indexing:
    • Example:
    • print(Mylist[0])print(Mylist[0])

Iterating Through a List

  • Accessing list values using a for loop allows for read-only access:
    • Example:
    • forextnameextinextMyList:for ext{ }name ext{ }in ext{ }MyList:
      • print(name)print(name)
  • Utilizing a while loop provides control over the loop index:
    • Example:
    • idx=0idx = 0
    • while ext{ }idx < len(MyList):
      • print(MyList[idx])print(MyList[idx])
      • idx=idx+1idx = idx + 1
  • Example List: MyList=["Neil","Garrett","Stacy","Vicki","Magnitude"]MyList = ["Neil", "Garrett", "Stacy", "Vicki", "Magnitude"]

List Operators

  • Available operators for lists include:
    • Concatenation:
    • The + operator combines two lists:
      • Example: list1+list2list1 + list2
    • Repetition:
    • The * operator repeats a list a defined number of times:
      • Example: listnlist * n
  • Both operators return a new list.

Boolean List Operators

  • in: Checks if a list contains a specific value, returning true or false:
    • Example:
    • ifext"Vicki"extinMyList:if ext{ }"Vicki" ext{ in } MyList:
      • print("FoundVicki")print("Found Vicki")
  • not in: Checks if a list does NOT contain a specific value, returning true or false:
    • Example:
    • ifext"Leonard"extnotinMyList:if ext{ }"Leonard" ext{ not in } MyList:
      • print("Leonardlikesthispost!")print("Leonard likes this post!")

List Indexing Operator

  • The [] operator retrieves individual values in a list by specifying the index:
    • Can also create slices (subsections of lists).
  • Slicing:
    • myList[start:stop]myList[start:stop]
    • Start: First index included
    • Stop: Up to, but NOT including, this index
  • Example of slicing:
    • MyList[1:3]MyList[1:3]["Garrett","Stacy"]["Garrett", "Stacy"]
    • MyList[:2]MyList[:2]["Neil","Garrett"]["Neil", "Garrett"]
    • MyList[3:]MyList[3:]["Vicki","Magnitude"]["Vicki", "Magnitude"]

In-Class Activity

  • Create a program that initializes a list:
    • [1,5,6,7,8,12,14,15,18,20][1, 5, 6, 7, 8, 12, 14, 15, 18, 20]
  • Iterate over the list, squaring each element, then slice the list and print elements 2-7:
    • Expected output: [36,49,64,144,196,225][36, 49, 64, 144, 196, 225]

Removing Items from a List

  • Using the del operator to erase an item by index:
    • Example:
    • T=[4,6,9]T = [4, 6, 9]
    • delT[1]<br/>ightarrowT=[4,9]del T[1] <br /> ightarrow T = [4, 9]
  • Can also remove a slice:
    • Example:
    • delMyList[2:5]del MyList[2:5] (This will remove the slice from index 2 to 5.)

Methods and Functions in Lists

  • Two categories exist: functions and methods.
  • Functions:
    • A named section of code callable with data input.
    • Example:
    • mylength=len(mylist)mylength = len(mylist)
  • Methods:
    • Special type of function initiated on a variable using the dot operator.
    • Example:
    • mylist.append(17)mylist.append(17)

List Methods

  • pop(): Removes an item by index and returns its value.
    • Example:
    • T=[4,6,9]T = [4, 6, 9]
    • x=T.pop(1)<br/>ightarrowT=[4,9],x=6x = T.pop(1) <br /> ightarrow T = [4, 9], x = 6
  • remove(value): Removes an item by value (not by index).
    • Example:
    • T=[4,6,9]T = [4, 6, 9]
    • T.remove(6)<br/>ightarrowT=[4,9]T.remove(6) <br /> ightarrow T = [4, 9]

Common List Methods

  • append(item): Adds an item to the end of the list.
    • Example:
    • list1=[8,43,120,4,33]list1 = [8, 43, 120, 4, 33]
    • list1.append(45)<br/>ightarrow[8,43,120,4,33,45]list1.append(45) <br /> ightarrow [8, 43, 120, 4, 33, 45]
  • index(item): Returns index of the first element equal to item; raises ValueError exception if not found.
    • Example:
    • list1.index(43)<br/>ightarrow1list1.index(43) <br /> ightarrow 1
  • insert(index, item): Inserts item at a specified index, shifts subsequent elements to the right.
    • Example:
    • list1.insert(2,10)<br/>ightarrow[8,43,10,120,4,33]list1.insert(2, 10) <br /> ightarrow [8, 43, 10, 120, 4, 33]

Additional Methods

  • sort(): Sorts list in ascending order.
    • Example:
    • list1=[8,43,120,4,33]list1 = [8, 43, 120, 4, 33]
    • list1.sort()<br/>ightarrow[4,8,33,43,120]list1.sort() <br /> ightarrow [4, 8, 33, 43, 120]
  • reverse(): Reverses the order of the list.
    • Example:
    • list1.reverse()<br/>ightarrow[33,4,120,43,8]list1.reverse() <br /> ightarrow [33, 4, 120, 43, 8]

List Functions

  • len(mylist): Returns the length of the list (number of items).
  • max(mylist): Returns the maximum value within the list.
  • min(mylist): Returns the minimum value within the list.
  • sum(mylist): Returns the sum of the values in the list.
    • Notably, these functions accept a list or a slice of a list as input.

In-Class Activity

  • In your main function:
    • Create a list with students' quiz grades:
    • [92,89,76,68,72,90,87,97,85][92, 89, 76, 68, 72, 90, 87, 97, 85]
    • Pass this list to a function that calculates the average, which should then be displayed to the user.
    • Do NOT use the built-in sum()sum() function.

Lists and Strings

  • Strings in Python share similarity with lists.
  • A string can be viewed as a list of characters:
    • Example:
    • "Spam"<br/>ightarrow[S,p,a,m]"Spam" <br /> ightarrow [‘S’, ‘p’, ‘a’, ‘m’]
  • A string can be transformed into a list:
    • Example:
    • A=list("Hello")A = list("Hello")A=[H,e,l,l,o]A = [‘H’, ‘e’, ‘l’, ‘l’, ‘o’]

Using Split and Join

  • split(): Converts a string into a list based on a specified delimiter.
    • Default delimiter is a space.
    • Example:
    • S="Wontchangehowmustardtastes"S = "Won’t change how mustard tastes"
      • myList=S.split()<br/>ightarrow["Wont","change","how","mustard","tastes"]myList = S.split() <br /> ightarrow ["Won’t", "change", "how", "mustard", "tastes"]
  • Commonly used to process CSV (comma-separated values) files.
  • join(): Reverses the process, combining a list into a string using a specified delimiter.
    • Example:
    • t=["Why","Go","Greendale?","Just","Because!"]t = ["Why", "Go", "Greendale?", "Just", "Because!"]
    • delim=""delim = " "
      • s=delim.join(t)<br/>ightarrow"WhygoGreendale?JustBecause!"s = delim.join(t) <br /> ightarrow "Why go Greendale? Just Because!"

In-class Activity

  • Write a function that takes in three parameters:
    • index1, index2, and a list.
    • Swap the values located at index1 and index2.

Additional In-Class Activity

  • Write a function that accepts a list and returns two values:
    • The minimum value in the list.
    • The index of the minimum value.

Challenge Activity

  • Develop a selection sort algorithm to sort values in an array:
    • Implement logic to continuously find the minimum value and swap it with the value at index 0, and subsequently with the others in subsequent iterations until the list is sorted.
  • Repeats this process for the second and third lowest values, positioning them in the appropriate respective indices.