Python Forum
trouble while appending list in for loop
Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
trouble while appending list in for loop
#1
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)
Reply
#2
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.
Reply


Possibly Related Threads…
Thread Author Replies Views Last Post
  trouble reading string/module from excel as a list popular_dog 0 424 Oct-04-2023, 01:07 PM
Last Post: popular_dog
  Time.sleep: stop appending item to the list if time is early quest 0 1,879 Apr-13-2021, 11:44 AM
Last Post: quest
  Reading and appending list MrSwiss 1 1,728 Mar-01-2021, 09:01 AM
Last Post: Serafim
  list trouble rediska 3 2,236 Oct-17-2020, 11:17 AM
Last Post: ibreeden
  Appending list Trouble Big Time Milfredo 7 3,113 Oct-01-2020, 02:59 AM
Last Post: Milfredo
  Appending to list of list in For loop nico_mnbl 2 2,368 Sep-25-2020, 04:09 PM
Last Post: nico_mnbl
  trouble with list array Milfredo 2 2,041 Sep-16-2020, 12:07 AM
Last Post: Milfredo
  Trouble with converting list , dict to int values! faryad13 7 3,763 Sep-04-2020, 06:25 AM
Last Post: faryad13
  Append list into list within a for loop rama27 2 2,385 Jul-21-2020, 04:49 AM
Last Post: deanhystad
  appending list of list glennford49 2 2,145 Mar-29-2020, 09:33 AM
Last Post: ibreeden

Forum Jump:

User Panel Messages

Announcements
Announcement #1 8/1/2020
Announcement #2 8/2/2020
Announcement #3 8/6/2020