2. LISTS
• Lists are used to store multiple items in a single variable. my_variable=8 my_list=[8,24,46,21]
• Lists are one of 4 built-in data types in Python used to store collections of data, the other 3 are Tuple,
Set, and Dictionary, all with different qualities and usage. We explicitly go over set and dictionary later
on in the semester.
• Lists are created using square brackets:
• Example
• thislist = [“Brady", “Manning", “Brees"]
• print(thislist)
3. LISTS
• List items are ordered, changeable, and allow duplicate values.
• List items are indexed, the first item has index [0], the second item has index [1] etc.
• my_list=[“Brady”, “Manning”, “Brees”]
• my_list2=[“Manning”, “Brady”, “Brady”]
• print(my_list)
• print(my_list2)
• What is the output of these two print statements?
• print(my_list2[0])
• print(my_list[1])
• What is the output of these two print statements?
4. LISTS
• Main thing to remember: lists contain multiple items, are ordered, can be duplicated, and be changed.
• They can be strings my_list=[“Brady”, “Manning”] or they can be numerical values my_list=[1,2]
5. COPYING LISTS
• The list variable does not contain the values of the list technically. It contains the reference to the list.
Meaning it contains the references to the index numbers of those values, and the values themselves are
stored in the memory.
• list=[“bob”,”karen”,”jake”]
Bob is index 0, karen 1, jake 2. Python will read the list variable name, see index 0, and then look up index 0 for
the list in its memory and give you the value “bob”. This is what is really happening behind the scenes.
• To copy a list, just set the new list name = to the original list.
cousins=list
If I print the cousins list, it should give me the same exact values of the list. This copy list is also referencing the
same index values, which python looks up in its memory. Modifying one list modifies the other. The have the
same indexes stored to its memory.
6. ACCESSING ITEMS IN LISTS
• As I showed you before, items in lists can be accessed through indexing
• my_list=["Rebecca","Steve","Jane","Antoine","Lorgal"]
• print(my_list[0]) prints Rebecca because its index is 0. What is the length of this list?
• You can specify a range of indexes by specifying where to start and where to end the range.
• When specifying a range, the return value will be a new list with the specified items.
my_list=["Rebecca","Steve","Jane","Antoine","Lorgal"]
print(my_list[1:3])
Output? It wants to print the values starting at index 1 and ends at index 3(not included). Remember it starts at index 0.
7. MORE INDEXING
• If you leave off the first number, it will start at index zero
• my_list=["Rebecca","Steve","Jane","Antoine","Lorgal"]
• print(my_list[:3])
• If you leave off the last number, it will end at the last index(this time included).
• my_list=["Rebecca","Steve","Jane","Antoine","Lorgal"]
• print(my_list[1:])
8. CHECKING TO SEE IF ITEM IS IN LIST
• To determine if a specified item is present in a list use the in keyword:
• my_list=["Rebecca","Steve","Jane","Antoine","Lorgal"]
• if "Jane" in my_list:
• print("Jane is in this class")
• else:
• print("Jane doesn't go to class")
• Output?
9. CHANGING LIST ITEM VALUES
• To change the value of a specific item, refer to the index number:
• my_list=["Vanilla","Brambleberry","Salted Caramel","Mint Chocolate Chip","Coffee"]
• my_list[0]="Chocolate"
• print(my_list)
• You just have to reference the index you want to change(in this case I wanted vanilla out of there) and
then set it equal to its new value(“Chocolate”). Now Chocolate is the first item in the list at index zero
10. CHANGING A RANGE OF VALUES
• my_list=["Vanilla","Brambleberry","Salted Caramel","Mint Chocolate Chip","Coffee"]
• my_list[1:3]="Chocolate","Cookies N' Cream"
• print(my_list)
• Output?
• As you can see indexing is important. Refer back to the book if you’re still a little iffy about it! If
requested, I can start off with a little indexing review next time.
11. INSERTING A VALUE
• Use .insert() When you want to add an item to a list without replacing an existing value.
• my_list=["Vanilla","Brambleberry","Salted Caramel","Mint Chocolate Chip","Coffee"]
• my_list.insert(2,”Neopolitan”)
• print(my_list)
Output?
After your list variable, add a .insert(). Inside the parentheses goes first the index numer, and then second
the value you want inserted.
12. APPEND
• When you want to add a item to your list, but its order doesn’t matter, you can use the .append
method. That item will be added to the end of the list.
• my_list=["Vanilla","Brambleberry","Salted Caramel","Mint Chocolate Chip","Coffee"]
• my_list.append("Pistachio")
• print(my_list)
Output?
13. CONCATENATING LISTS
• Concatenating lists is quite easy!
• Say if you have two lists, list and list2, and you want to add them together, you just use the addition
operator(+) to add them together
• list=[1,2,3]
• list2=[4,5,6]
• print(list + list2)
output?
Note this isn’t adding the values, its concantenating. This is also another way of saying appending lists.
Because the values of list2 will come after the values of list
14. REMOVING ITEMS
• Three ways to remove items in lists:remove, pop, and clear.
• Remove deletes a specific value, pop removes a specified index, and clear clears the entire list.
• my_list=["Physics","Calculus 2","CSC1302","Humanities"]
• my_list.remove("Physics")
• print(my_list)
• my_list=["Physics","Calculus 2","CSC1302","Humanities"]
• my_list.pop(1)
• print(my_list)
• my_list=["Physics","Calculus 2","CSC1302","Humanities"]
• my_list.clear()
• print(my_list)
• Output?
15. SUM, MAX, MIN
• Three functions you can use to play around with numerical lists is sum, max, min.
• sum() finds the sum. list=[1,2,3) print(sum(list))= ?
• max() finds the max. List=[4,6,1] print(max(list)) = ?
list=[“bob”,”jake”,”karen”] print(max(list))= ? What is the max when it comes to a string?
• min() finds the min. list=[123,122,119] print(min(list))=?
• What would be the min in the list with the 3 names, bob jake, and karen?
• I vaguely remember strings being involved in maybe 1 or two quiz or test questions. It’s important to know that strings have values to
them too. a comes before b. 3 letters is less than 4. bob and ken have the same number of letters, but if I used the min function to
the find the minimum between these two strings, bob would be the min. Because b comes before k. Understand this.
16. SORT
• So now that we have learned about values, the sort method might make more sense.
• The .sort() method sorts a list from least to greatest value. Remember the . If you want to use this
method, place it after your list name.
• list=[56,78,1,25,24,5]
• print(list.sort())
• Output?
17. LOOPING THROUGH LISTS
• You can loop through the list items by using a for loop. This will print all items in the list, one by one:
• thislist = ["apple", "banana", "cherry"]
• for x in thislist:
• print(x)
What do you think this will look like? Iterating through lists with for loops is common.
18. LOOP THROUGH INDEX NUMBERS
• You can also loop through the list items by referring to their index number.
• Use the range() and len() functions to create a suitable iterable.
• Print all items by referring to their index number:
• thislist = ["apple", "banana", "cherry"]
• for i in range(len(thislist)):
• print(thislist[i])
Output [0,1,2]
19. ITERATING THROUGH LIST WITH WHILE LOOP
• You can loop through the list items by using a while loop.
• Use the len() function to determine the length of the list, then start at 0 and loop your way through the list
items by referring to their indexes.
• Remember to increase the index by 1 after each iteration.
• Print all items, using a while loop to go through all the index numbers
• thislist = ["apple", "banana", "cherry"]
• i = 0
• while i < len(thislist):
• print(thislist[i])
• i = i + 1
20. FILLING AN EMPTY LIST
• A lot of times you will want to have python fill a list for you. Maybe you want to store multiple input values from a user and
store them in a list. To do this, first create an empty list.
• list=[]
• MAX=5
• for i in range(MAX):
• userInput=int(input("Please enter a number : "))
• list.append(userInput)
• print(list)
A for loop will continue forever. To stop this, I created a constant variable MAX. In the for loop I specified the range to be 5, so it
will stop after 5 iterations. Meaning it will ask my input 5 times. I will put in 5 numbers, and it will append them to the list,
filling it out.
21. FILLING AN EMPTY LIST
• i=0
• list=[]
• while i<5:
• userInput=int(input("Please enter a number : "))
• list.append(userInput)
• i=i+1
• print(list)
• This accomplishes the same exact task of filling an empty list out, this time we used a while loop with a counter variable. Instead of
setting a constant variable and telling it when to stop, we set i=0 and add 1 each time the loop iterates. Once it reaches 5, the loop
terminates. Each item iterated over is added to the list.
22. FILLING LISTS
• values = []
• print("Please enter values, Q to quit:")
• userInput = input("")
• while userInput.upper() != "Q" :
• values.append(float(userInput))
• userInput = input("")
• This is the third way to fill a list with user input, and probably the best way. You do not have to set a value for
it to end, because we are using a sentinel value(in this case “Q”). The user keeps entering values until they are
finished, and when they enter Q, the program terminates the loop and will print out the appended list.
23. LISTS AND FUNCTIONS
• We can use lists in our functions! Everything works together in tandem.
values=[1,4,6,26,15]
values2=[72,56,21,52]
newlist=values+values2
def find_sum(values):
return sum(values)
print(find_sum(values))
24. FUNCTIONS AND LISTS CONTINUED
• values=[1,4,6,26,15]
• values2=[72,56,21,52]
• newlist=values+values2
• def append_lists(values,values2):
• newlist=values+values2
• return values+values2