Presentation is loading. Please wait.

Presentation is loading. Please wait.

Lists CMSC 201. Overview Today we will learn about: For loops.

Similar presentations


Presentation on theme: "Lists CMSC 201. Overview Today we will learn about: For loops."— Presentation transcript:

1 Lists CMSC 201

2 Overview Today we will learn about: For loops

3 Motivation A lot of times, we have a pattern like this: a = 0 myList = [1, 2, 3] while a < len(myList): print(myList[a]) This is a way we can iterate over a list.

4 For Loops For loops give us a faster way of doing the same thing! myList = [1, 2, 3] for listItem in myList: print listItem

5 For Loops myList = [1, 2, 3] for listItem in myList: print listItem In the for loop, we are declaring a new variable called “listItem”. The for loop is going to be changing this for us! The first time through the loop, listItem will be the first element of the list. The second time through the loop, it will be the second element, and so on until the list is done.

6 Example Finding the average using for loops: myList = [1, 2, 3, 4] sum = 0 for listItem in myList: sum = listItem + sum print(sum / len(myList)

7 A Downside! What do you think this code does? myList = [1, 2, 3, 4] for listItem in myList: listItem = 4 print(myList)

8 A Downside! What do you think this code does? myList = [1, 2, 3, 4] for listItem in myList: listItem = 4 print(myList) Prints: [1, 2, 3, 4]

9 A Downside! What do you think this code does? myList = [1, 2, 3, 4] for listItem in myList: listItem = 4 print(myList) Changing listItem DOES NOT CHANGE THE ORIGINAL LIST! listItem is just a copy of each element.

10 For Loop Trick Frequently we want to do something like this: a = 0 while a < 10: print(a) a = a + 1 A lot of times, we want loops that count.

11 For Loop Trick There is a built in python function that gives you a list of numbers! a = range(0, 10) print(a) Prints: [0, 1, 2, 3, 4, 5, 6, 7, 8, 9] The range function gives you a list of numbers between the first number (inclusive) and the second number (exclusive)

12 For Loop Trick a = range(0, 10) print(a) So now we can create a list of numbers. Any ideas what we can do with that?

13 For Loop Trick for num in range(0, 10): print(num) An easier way to make a counting loop! Prints:

14 For Loop Trick We can even count by whatever number we want! for num in range(0, 10, 2): print(num) Prints:

15 Summary: For loops: Use for iterating over lists Also use in situations where we want loops to count. While loops: Use when we have some condition that doesn’t fall into the previous two categories.


Download ppt "Lists CMSC 201. Overview Today we will learn about: For loops."

Similar presentations


Ads by Google