Welcome to the Treehouse Community

Want to collaborate on code errors? Have bugs you need feedback on? Looking for an extra set of eyes on your latest project? Get support with fellow developers, designers, and programmers of all backgrounds and skill levels here with the Treehouse Community! While you're at it, check out some resources Treehouse students have shared here.

Looking to learn something new?

Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and join thousands of Treehouse students and alumni in the community today.

Start your free trial

Python Python Basics (2015) Logic in Python Around and Around

How does python know what "number (or 'num')" is when writing a loop?

For example:

numbers = [1, 2, 3, 4]
doubles = []
for number in numbers:

I don't get how python understands what "number" is in this. How does python interpret this code to understand that you are referring to the numbers within the list?

3 Answers

Aaron Price
Aaron Price
5,974 Points

Ugh that confused me for so long! In other languages. Disclaimer, I haven't glanced at python in ages, but I'm pretty sure the following is true. Someone correct me if I'm wrong.

It's just a variable, you don't have to call it "number". It might be easier to understand if you call it something completely different just to illustrate a point.

numbers = [1,2,3,4]
doubles = []
for myVariable in numbers:
  doubles.append(myVariable * 2)

So it just loops through the array, and with every iteration, it assigns myVariable to the value of that item in the array. It's practically doing this automatically

myVariable = 1
doubles.append(myVariable * 2)

myVariable = 2
doubles.append(myVariable * 2)

myVariable = 3
doubles.append(myVariable * 2)

myVariable = 4
doubles.append(myVariable * 2)

Thank you for your answer! That makes sense!

28,558 Points

Python understand what number is because the for loop creates it. The way a for loop works is that each time it runs it pulls out an item from a list you specify and assigns it within the loop to a variable you specify.

So for number in numbers is a loop that says take the items from a list called numbers, and pull them out one by one and assign them to the variable number.

The first time the loop runs your code number will contain the first item of numbers, the second time the loop runs it will contain the second item of numbers and so on, until it has run though all of the items.

Awesome. That made it perfectly clear! Thanks!!

thnx andren that makes perfect sense