BeFOR we Begin


#1

Could any one explain why this is happening?
My code is :
names = ["Adam","Alex","Mariah","Martine","Columbus"]

for name in names:
    print names

And the output is:

['Adam', 'Alex', 'Mariah', 'Martine', 'Columbus']
['Adam', 'Alex', 'Mariah', 'Martine', 'Columbus']
['Adam', 'Alex', 'Mariah', 'Martine', 'Columbus']
['Adam', 'Alex', 'Mariah', 'Martine', 'Columbus']
['Adam', 'Alex', 'Mariah', 'Martine', 'Columbus']
None

Could anyone tell to me why it is printed 5 times?
Any help will be appreciated
Thanks.


#2

Hi you should print name


#3

yeah dude i got that !. But why when i put names it gets printed out 5 times.
Thanks.


#4

There are 5 names. For each name, it prints out all the names and seeing that there are 5 names then it prints all the names 5 times.

If that doesn't help, another way to see why is if you break down the 'for' loop:

hope this helps :slightly_smiling:


#5

Got that dude ! .
Thank You


#6

@boyzac2 I don't really think the code you gave is correct in visualizing the problem, in that code, you made 5 loops, each of which ran for 5 times, and printed names inside each loop. That should output names a total of 25 times (afaik).

@zeeshu619 Interpret:

names = ["Adam","Alex","Mariah","Martine","Columbus"] 
# remember that there are five individual `name`s inside `names`
for name in names:
    print names

like this:

for each name in names (that means 5 times), print out the entire names list


#7

Yeah, I agree with you. I was well aware that there were 5 loops but at the time I couldn't think of a better way to explain it.


#8

3 posts were split to a new topic: It looks like your code did not print "Adam" - error on BeFOR we Begin


#9

Thank you very much @gaurangtandon good explanation .!!! :smiley:


#10

for name in names:
print name


#11

hi
that it's what i do, before i saw your solution. and it doesn't work.

names = ["Adam","Alex","Mariah","Martine","Columbus"]
for i in names:
    print names

and i get the error : Oops, try again. It looks like your code did not print "Adam".

and there is the output:

['Adam', 'Alex', 'Mariah', 'Martine', 'Columbus']
['Adam', 'Alex', 'Mariah', 'Martine', 'Columbus']
['Adam', 'Alex', 'Mariah', 'Martine', 'Columbus']
['Adam', 'Alex', 'Mariah', 'Martine', 'Columbus']
['Adam', 'Alex', 'Mariah', 'Martine', 'Columbus']
None

thanks


#12

You have to print each name separately not the entire names array.


#13

i print i, and this is the correct answer
:slight_smile:


#14