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?
(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 = []

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:
Or a bit more compact:

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

my_data = [value for value in output(10)]
My code examples are always for Python >=3.6.0
Almost dead, but too lazy to die:
All humans together. We don't need politicians!

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
  print function output wrong with strings. mposwal 5 523 Feb-12-2021, 09:04 AM
Last Post: DPaul
  How to append multiple <class 'str'> into a single List ahmedwaqas92 2 508 Jan-07-2021, 08:17 AM
Last Post: ahmedwaqas92
  Output with none, print(x) in function Vidar567 3 417 Nov-24-2020, 05:40 PM
Last Post: deanhystad
  output correction using print() function afefDXCTN 2 2,138 Oct-13-2020, 12:58 PM
Last Post: cvilao
  Append list into list within a for loop rama27 2 737 Jul-21-2020, 04:49 AM
Last Post: deanhystad
  Append only adding the same list again and again viraj1123 4 692 Jun-17-2020, 07:26 AM
Last Post: viraj1123
  Cant Append a word in a line to a list err "str obj has no attribute append Sutsro 2 710 Apr-22-2020, 01:01 PM
Last Post: deanhystad
  json.dumps list output qurr 12 1,749 Apr-08-2020, 10:13 PM
Last Post: micseydel
  If item in list = true, Output = xx kroh 0 574 Feb-19-2020, 09:17 AM
Last Post: kroh
  Problem with append list in loop michaelko03 0 642 Feb-16-2020, 07:04 PM
Last Post: michaelko03

Forum Jump:

User Panel Messages

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