Udacity CS 101: Lists Part III (Loops and Pop)

We learned about the while loops, which tests an expression and executes the code block below. Here we’ll meet a new kind of loop, called the for loop. The for loop is especially useful for list:

oddNumbers = [1,3,5,[7,9]]

for num in oddNumbers:

print num

# this will output:

# 1

# 3

# 5

# [7,9]

We are then introduced to a new method that lists provide, called index(), which takes as an argument the value you want to find in the list:

oddNumbers = [1,3,5,[7,9]]

print oddNumbers.index(3) # will give us 1

print oddNumbers.index(2) # will give us an error

Another interesting way to see if an element is inside a list is using the in operator:

oddNumbers = [1,3,5,[7,9]]

print 3 in oddNumbers # will print True

print 2 in oddNumbers # will print False

print 3 not in oddNumbers # will print False

print 2 not in oddNumbers # will print True

So both of these methods are similar in that they can help you find out if a certain element is in the list, the difference is that one tells you the first position where it is found, and the other just tells you if it is found.

A new method introduced here is pop(), it first mutates the list by removing the last element, and this methods returns that last element. Think of pop() as a pair of scissors, when you use it, it snips off the last elements of a list, and you will have that last element. Snippy!

oddNumbers = [1,3,5]

scissors = oddNumbers.pop()

print oddNumbers # will give you [1,3]

print scissors # will give you 5

This Udacity post references Udacity CS 101 Unit 3 Chapters 22, 23, 24, 25, 26, 27, 28, 29, 30 and 31.
Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s