Python Forum

Full Version: trouble while appending list in for loop
You're currently viewing a stripped down version of our content. View the full version with proper formatting.
Hi folks, I am new to python and having trouble to append list in for loop.. any help will be appreciated!

a = [1,1,2,3,5,8,13,21,34,55,89] def less_than_ten(num): for n in a: if n < 10: print(n) less_than_ten(a) def less_than_five(num): b = [] for n in a: if n < 5: # print(n) global b.append(n) # is giving error at (.) in this line print(b) less_than_five(a)

Its working now but still the print command works at position 1 which print after each iteration but is not printing on Position 2..(can anyone please explain why is that?)
a = [1,1,2,3,5,8,13,21,34,55,89] pick_number = int(input("enter the number:")) b = [] def less_than(num): for n in a: if n < pick_number: b.append(n) print (b) #position 1 print(b) # position 2 less_than(a)
This question exists due to some lacks in understanding of code execution model in Python.

When you execute your piece of code, Python do the following:
1) creates list <a>
2) asks to enter the number <pick_number>
3) defines a function (lines 6 to 11); Note: Python don't execute this function
4) print current value of b (it is an empty list) (line 12)
5) executes function <less_than> (line 15)

So, to print filled array <b>, just swap line 12 and line 15.