user603709 user603709 - 4 months ago 5
Python Question

Some anomaly in printing result for list

Hi I have two list snip and phras. I tried to run them in for loop in two different ways. I was expecting them to give the same output but they are giving different. How so ?

snip = ['Hi john', 'Hi sam', 'Hi lila']
phras = ['lets play','lets paint']
for s in snip,phras:
result = s[:]

print result # output is ['lets play', 'lets paint']

# Now lets run again

snip = ['Hi john', 'Hi sam', 'Hi lila']
phras = ['lets play','lets paint']
for s in snip,phras:
result = s[:]
print result

#output is ['Hi john', 'Hi sam', 'Hi lila']
# ['lets play','lets paint']

Answer

Your print statement is outside of your first loop so it only shows the last value assigned to result whereas the second print statement is inside of the loop and therefore prints each value of result

Comments