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

Michael Rathbun
Michael Rathbun
1,624 Points

Can anyone explain this example in the teachers notes ?

I normally look at the teachers notes for guidance, but these have me confused more.

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

1 Answer

andren
andren
28,558 Points
numbers = [1, 2, 3, 4] # Create an array with 4 numbers
doubles = [] # Create an empty array
for number in numbers: # Loop though that array and pull out individual numbers into the variable number
    doubles.append(number*2) # Append the individual number * 2 to the doubles array
# After the loop doubles will contain [2, 4, 6, 8] which is each number multiplied by two.

The way a for each loop works is that it takes a list, numbers in this case. And pulls out each individual item from the list and stores it in a variable you define, number in this case.

The first time the loop runs through your code number will equal the first item in the numbers array, the second time it will equal the second item, and so on until it has gone through all of the items.

That means that the above code is essentially doing exactly the same as this code:

numbers = [1, 2, 3, 4] # Create an array with 4 numbers
doubles = [] # Create an empty array

number = numbers[0] # Set number to first item of numbers
doubles.append(number*2) # Append the individual number * 2 to the doubles array

number = numbers[1] # Set number to second item of numbers
doubles.append(number*2) # Append the individual number * 2 to the doubles array

number = numbers[2] # Set number to third item of numbers
doubles.append(number*2) # Append the individual number * 2 to the doubles array

number = numbers[3] # Set number to fourth item of numbers
doubles.append(number*2) # Append the individual number * 2 to the doubles array

So the loop simply changes the number variable each time it runs the code you have provided, so that you end up running your code on each individual item in the list.

Michael Rathbun
Michael Rathbun
1,624 Points

Thanks this helped a lot ! Very in depth.