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] [ 1 , 2 , 3 , 4 , 5 ] [ " H e l l o " , " T h i s " , " i s " , " a " , " l i s t " , " o f " , " s t r i n g s " ] ["Hello", "This", "is", "a", "list", "of", "strings"] [ " He ll o " , " T hi s " , " i s " , " a " , " l i s t " , " o f " , " s t r in g s " ] [ ] [] [ ] (an empty list) Lists can contain any data type and can include mixed data types: Example: [ " H e l l o " , 1 , 2 , 3.7 , [ " a l i s t " , " i n s i d e a l i s t " ] ] ["Hello", 1, 2, 3.7, ["a list", "inside a list"]] [ " He ll o " , 1 , 2 , 3.7 , [ " a l i s t " , " in s i d e a l i s t " ]] Declaring a variable of list type: Example: M y l i s t = [ 37 , 42 , 64 , 12 , 37 ] Mylist = [37, 42, 64, 12, 37] M y l i s t = [ 37 , 42 , 64 , 12 , 37 ] Accessing Values in a List To access or modify a value within a list, use the syntax: l i s t N a m e [ i n d e x ] listName[index] l i s tN am e [ in d e x ] Indexing conventions: Starts at 0 and ends at (number of items - 1). Access examples: M y l i s t = [ 42 , 37 , 64 , 12 , 37 ] Mylist = [42, 37, 64, 12, 37] M y l i s t = [ 42 , 37 , 64 , 12 , 37 ] L a s t e x t v a l u e = M y l i s t [ 4 ] < b r / > i g h t a r r o w 37 Last ext{ }value = Mylist[4] <br />
ightarrow 37 L a s t e x t v a l u e = M y l i s t [ 4 ] < b r / > i g h t a rro w 37 F i r s t e x t v a l u e = M y l i s t [ 0 ] < b r / > i g h t a r r o w 42 First ext{ }value = Mylist[0] <br />
ightarrow 42 F i rs t e x t v a l u e = M y l i s t [ 0 ] < b r / > i g h t a rro w 42 Using variables for indexing: Example: i = 2 i = 2 i = 2 v a l = M y l i s t [ i ] < b r / > i g h t a r r o w 64 val = Mylist[i] <br />
ightarrow 64 v a l = M y l i s t [ i ] < b r / > i g h t a rro w 64 v a l = M y l i s t [ i + 1 ] < b r / > i g h t a r r o w 12 val = Mylist[i+1] <br />
ightarrow 12 v a l = M y l i s t [ i + 1 ] < b r / > i g h t a rro w 12 Modifying values in a list: Example: M y l i s t [ 3 ] = 17 < b r / > i g h t a r r o w M y l i s t = [ 42 , 37 , 64 , 17 , 37 ] Mylist[3] = 17 <br />
ightarrow Mylist = [42, 37, 64, 17, 37] M y l i s t [ 3 ] = 17 < b r / > i g h t a rro wM y l i s t = [ 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: M y l i s t = [ 42 , 37 , 64 , 12 , 37 ] Mylist = [42, 37, 64, 12, 37] M y l i s t = [ 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: M y l i s t [ 6 ] Mylist[6] M y l i s t [ 6 ] → ERROR: index out of bounds Utilize the built-in l e n ( ) len() l e n ( ) function to determine list size: Example: p r i n t ( M y l i s t [ l e n ( M y l i s t ) − 1 ] ) print(Mylist[len(Mylist) - 1]) p r in t ( M y l i s t [ l e n ( M y l i s t ) − 1 ]) Printing a List The print function can display entire lists in square brackets. Example: M y l i s t = [ 42 , 37 , 64 , 12 , 37 ] Mylist = [42, 37, 64, 12, 37] M y l i s t = [ 42 , 37 , 64 , 12 , 37 ] p r i n t ( M y l i s t ) print(Mylist) p r in t ( M y l i s t ) → Output: [ 42 , 37 , 64 , 12 , 37 ] [42, 37, 64, 12, 37] [ 42 , 37 , 64 , 12 , 37 ] Printing a single value using indexing: Example: p r i n t ( M y l i s t [ 0 ] ) print(Mylist[0]) p r in t ( M y l i s t [ 0 ]) Iterating Through a List Accessing list values using a for loop allows for read-only access: Example: f o r e x t n a m e e x t i n e x t M y L i s t : for ext{ }name ext{ }in ext{ }MyList: f ore x t nam ee x t in e x t M y L i s t : p r i n t ( n a m e ) print(name) p r in t ( nam e ) Utilizing a while loop provides control over the loop index: Example: i d x = 0 idx = 0 i d x = 0 while ext{ }idx < len(MyList): p r i n t ( M y L i s t [ i d x ] ) print(MyList[idx]) p r in t ( M y L i s t [ i d x ]) i d x = i d x + 1 idx = idx + 1 i d x = i d x + 1 Example List: M y L i s t = [ " N e i l " , " G a r r e t t " , " S t a c y " , " V i c k i " , " M a g n i t u d e " ] MyList = ["Neil", "Garrett", "Stacy", "Vicki", "Magnitude"] M y L i s t = [ " N e i l " , " G a rre tt " , " St a cy " , " Vi c ki " , " M a g ni t u d e " ] List Operators Available operators for lists include:Concatenation : The + operator combines two lists: Example: l i s t 1 + l i s t 2 list1 + list2 l i s t 1 + l i s t 2 Repetition : The * operator repeats a list a defined number of times: Example: l i s t ∗ n list * n l i s t ∗ n Both operators return a new list. Boolean List Operators in : Checks if a list contains a specific value, returning true or false: Example: i f e x t " V i c k i " e x t i n M y L i s t : if ext{ }"Vicki" ext{ in } MyList: i f e x t " Vi c ki " e x t in M y L i s t : p r i n t ( " F o u n d V i c k i " ) print("Found Vicki") p r in t ( " F o u n d Vi c ki " ) not in : Checks if a list does NOT contain a specific value, returning true or false: Example: i f e x t " L e o n a r d " e x t n o t i n M y L i s t : if ext{ }"Leonard" ext{ not in } MyList: i f e x t " L eo na r d " e x t n o t in M y L i s t : p r i n t ( " L e o n a r d l i k e s t h i s p o s t ! " ) print("Leonard likes this post!") p r in t ( " L eo na r d l ik es t hi s p os t ! " ) List Indexing Operator The [] operator retrieves individual values in a list by specifying the index: Can also create slices (subsections of lists). Slicing: m y L i s t [ s t a r t : s t o p ] myList[start:stop] m y L i s t [ s t a r t : s t o p ] Start: First index included Stop: Up to, but NOT including, this index Example of slicing: M y L i s t [ 1 : 3 ] MyList[1:3] M y L i s t [ 1 : 3 ] → [ " G a r r e t t " , " S t a c y " ] ["Garrett", "Stacy"] [ " G a rre tt " , " St a cy " ] M y L i s t [ : 2 ] MyList[:2] M y L i s t [ : 2 ] → [ " N e i l " , " G a r r e t t " ] ["Neil", "Garrett"] [ " N e i l " , " G a rre tt " ] M y L i s t [ 3 : ] MyList[3:] M y L i s t [ 3 : ] → [ " V i c k i " , " M a g n i t u d e " ] ["Vicki", "Magnitude"] [ " Vi c ki " , " M a g ni t u d e " ] 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] [ 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] [ 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] T = [ 4 , 6 , 9 ] d e l T [ 1 ] < b r / > i g h t a r r o w T = [ 4 , 9 ] del T[1] <br />
ightarrow T = [4, 9] d e lT [ 1 ] < b r / > i g h t a rro wT = [ 4 , 9 ] Can also remove a slice: Example: d e l M y L i s t [ 2 : 5 ] del MyList[2:5] d e lM y L i s t [ 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: m y l e n g t h = l e n ( m y l i s t ) mylength = len(mylist) m y l e n g t h = l e n ( m y l i s t ) Methods : Special type of function initiated on a variable using the dot operator. Example: m y l i s t . a p p e n d ( 17 ) mylist.append(17) m y l i s t . a pp e n d ( 17 ) List Methods pop() : Removes an item by index and returns its value. Example: T = [ 4 , 6 , 9 ] T = [4, 6, 9] T = [ 4 , 6 , 9 ] x = T . p o p ( 1 ) < b r / > i g h t a r r o w T = [ 4 , 9 ] , x = 6 x = T.pop(1) <br />
ightarrow T = [4, 9], x = 6 x = T . p o p ( 1 ) < b r / > i g h t a rro wT = [ 4 , 9 ] , x = 6 remove(value) : Removes an item by value (not by index). Example: T = [ 4 , 6 , 9 ] T = [4, 6, 9] T = [ 4 , 6 , 9 ] T . r e m o v e ( 6 ) < b r / > i g h t a r r o w T = [ 4 , 9 ] T.remove(6) <br />
ightarrow T = [4, 9] T . re m o v e ( 6 ) < b r / > i g h t a rro wT = [ 4 , 9 ] Common List Methods append(item) : Adds an item to the end of the list. Example: l i s t 1 = [ 8 , 43 , 120 , 4 , 33 ] list1 = [8, 43, 120, 4, 33] l i s t 1 = [ 8 , 43 , 120 , 4 , 33 ] l i s t 1. a p p e n d ( 45 ) < b r / > i g h t a r r o w [ 8 , 43 , 120 , 4 , 33 , 45 ] list1.append(45) <br />
ightarrow [8, 43, 120, 4, 33, 45] l i s t 1. a pp e n d ( 45 ) < b r / > i g h t a rro w [ 8 , 43 , 120 , 4 , 33 , 45 ] index(item) : Returns index of the first element equal to item; raises ValueError exception if not found. Example: l i s t 1. i n d e x ( 43 ) < b r / > i g h t a r r o w 1 list1.index(43) <br />
ightarrow 1 l i s t 1. in d e x ( 43 ) < b r / > i g h t a rro w 1 insert(index, item) : Inserts item at a specified index, shifts subsequent elements to the right. Example: l i s t 1. i n s e r t ( 2 , 10 ) < b r / > i g h t a r r o w [ 8 , 43 , 10 , 120 , 4 , 33 ] list1.insert(2, 10) <br />
ightarrow [8, 43, 10, 120, 4, 33] l i s t 1. in ser t ( 2 , 10 ) < b r / > i g h t a rro w [ 8 , 43 , 10 , 120 , 4 , 33 ] Additional Methods sort() : Sorts list in ascending order. Example: l i s t 1 = [ 8 , 43 , 120 , 4 , 33 ] list1 = [8, 43, 120, 4, 33] l i s t 1 = [ 8 , 43 , 120 , 4 , 33 ] l i s t 1. s o r t ( ) < b r / > i g h t a r r o w [ 4 , 8 , 33 , 43 , 120 ] list1.sort() <br />
ightarrow [4, 8, 33, 43, 120] l i s t 1. sor t ( ) < b r / > i g h t a rro w [ 4 , 8 , 33 , 43 , 120 ] reverse() : Reverses the order of the list. Example: l i s t 1. r e v e r s e ( ) < b r / > i g h t a r r o w [ 33 , 4 , 120 , 43 , 8 ] list1.reverse() <br />
ightarrow [33, 4, 120, 43, 8] l i s t 1. re v erse ( ) < b r / > i g h t a rro w [ 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] [ 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 s u m ( ) sum() s u m ( ) function. Lists and Strings Strings in Python share similarity with lists. A string can be viewed as a list of characters: Example: " S p a m " < b r / > i g h t a r r o w [ ‘ S ’ , ‘ p ’ , ‘ a ’ , ‘ m ’ ] "Spam" <br />
ightarrow [‘S’, ‘p’, ‘a’, ‘m’] " Sp am " < b r / > i g h t a rro w [ ‘ S ’ , ‘ p ’ , ‘ a ’ , ‘ m ’ ] A string can be transformed into a list: Example: A = l i s t ( " H e l l o " ) A = list("Hello") A = l i s t ( " He ll o " ) → A = [ ‘ H ’ , ‘ e ’ , ‘ l ’ , ‘ l ’ , ‘ o ’ ] 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 = " W o n ’ t c h a n g e h o w m u s t a r d t a s t e s " S = "Won’t change how mustard tastes" S = " W o n ’ t c han g e h o w m u s t a r d t a s t es " m y L i s t = S . s p l i t ( ) < b r / > i g h t a r r o w [ " W o n ’ t " , " c h a n g e " , " h o w " , " m u s t a r d " , " t a s t e s " ] myList = S.split() <br />
ightarrow ["Won’t", "change", "how", "mustard", "tastes"] m y L i s t = S . s pl i t ( ) < b r / > i g h t a rro w [ " W o n ’ t " , " c han g e " , " h o w " , " m u s t a r d " , " t a s t es " ] 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 = [ " W h y " , " G o " , " G r e e n d a l e ? " , " J u s t " , " B e c a u s e ! " ] t = ["Why", "Go", "Greendale?", "Just", "Because!"] t = [ " Wh y " , " G o " , " G ree n d a l e ? " , " J u s t " , " B ec a u se ! " ] d e l i m = " " delim = " " d e l im = "" s = d e l i m . j o i n ( t ) < b r / > i g h t a r r o w " W h y g o G r e e n d a l e ? J u s t B e c a u s e ! " s = delim.join(t) <br />
ightarrow "Why go Greendale? Just Because!" s = d e l im . j o in ( t ) < b r / > i g h t a rro w " Wh y g o G ree n d a l e ? J u s tB ec a u se ! " 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. Knowt Play Call Kai