Python Forum
How to append to list a function output?
Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
How to append to list a function output?
#6
(Aug-24-2020, 09:42 AM)rama27 Wrote:
 
def output(n):
    i = n
    for i in range(0, n-1):
        return i
        i +=1 # <-- has no effect because the name i
              # is assigned by the for-loop
              # the name i is overwritten with the next value from
              # the range generator
              # this is not required

arr = []
arr.append(output(10)) 

The return statement return a value and the function is left.
Instead, you can convert your function to a generator.
The keyword yield yields something, but does not close the generator context.

Your function as a generator:

def output(n):
    i = n
    for i in range(0, n-1):
        yield i
Calling the function, returns a generator.
You can iterate over a generator.

my_generator = output(10)

my_data = []
for value in my_generator:
    print(value)
    my_data.append(value)
Or a bit more compact:


my_data = []
for value in output(10):
    print(value)
    my_data.append(value)
And as a list comprehension:

my_data = [value for value in output(10)]
Almost dead, but too lazy to die: https://sourceserver.info
All humans together. We don't need politicians!
Reply


Messages In This Thread
RE: How to append to list a function output? - by DeaD_EyE - Aug-24-2020, 10:53 AM

Possibly Related Threads…
Thread Author Replies Views Last Post
  append str to list in dataclass flash77 6 345 Mar-14-2024, 06:26 PM
Last Post: flash77
  problem in output of a function akbarza 9 1,096 Sep-29-2023, 11:13 AM
Last Post: snippsat
Question How to append integers from file to list? Milan 8 1,366 Mar-11-2023, 10:59 PM
Last Post: DeaD_EyE
  How to print the output of a defined function bshoushtarian 4 1,237 Sep-08-2022, 01:44 PM
Last Post: deanhystad
  read a text file, find all integers, append to list oldtrafford 12 3,373 Aug-11-2022, 08:23 AM
Last Post: Pedroski55
  Using .append() with list vs dataframe Mark17 7 9,910 Jun-12-2022, 06:54 PM
Last Post: Mark17
  sum() list from SQLAlchemy output Personne 5 4,346 May-17-2022, 12:25 AM
Last Post: Personne
  output correction using print() function afefDXCTN 3 10,966 Sep-18-2021, 06:57 PM
Last Post: Sky_Mx
  python prints none in function output chairmanme0wme0w 3 2,160 Jul-07-2021, 05:18 PM
Last Post: deanhystad
  print function output wrong with strings. mposwal 5 3,047 Feb-12-2021, 09:04 AM
Last Post: DPaul

Forum Jump:

User Panel Messages

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