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?
Hi, I have a following issue. I need to append a function's output into a list. See a simplified code bellow:

def output(n):
    i = n
    for i in range(0, n-1):
        i +=1


arr = []
However, my arr list is still empty. How can I fix it please? Thanks a lot!
You do not specify a return value for Output, so it returns None. Your arr is not empty, it contains None.

print does exactly what it says; print. It does not change a variable. It does not return a value from a function. print just prints something to stdout or stderr or to a file.

Your output function doesn't make any sense. Not only does it not return a value, but I cannot thing of what kind of value it would return.

What do you want to do? Explain that and you will get a better answer.
You're not returning anything. Also in the for loop replace that i with "_" as you're not using that variable and it would interfere with the one you defined before hand. The print function will only send the value to the console to display it. Also if you plan on adding all those values into the list, then you'll have to first put all those values into a list inside the function, and then return the list. You can then define arr as arr = output(10) but if you want to append the list of numbers to arr then you can change them to tuples and add them together, since lists cannot be added together list(tuple(arr)+tuple(output(10))). Though if you're just trying to get a list of numbers in a certain range you can just do list(range(0, 10)). Now since you probably don't know what the return is, I'll give an example:
import random

def add_two_random_numbers():
    return random.randint(1, 5) + random.randint(1, 5) # random.randint(1, 5) return a random number between 1 and 5. They are then added together and returned

def return_two_random_numbers():
    return random.randint(1, 5), random.randint(1, 5) # You can also return two or more values through commas

def return_nothing():
    return # Someimes you want to use a return function just to exit out of the function and return back
    print("returned") # Which is why anything after the return function will not execute

number1, number2 = return_two_random_numbers() # You can store the return values this way if you'd like
numbers = return_two_random_numbers() # Or you can also store them this way, in which they will be returned as a tuple
print(number1, number2, numbers)
5 3 2 (4, 4) None
Age Doesn't Matter, Your Passion Does
- Shreya Jain
Thank you @deanhystad for reply!

My desired output is a list [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]. Of course, I know I can do it by
 list(range(0, 10)) 
, but this is just an example of something more complicated.

When I arrange my example to:

def output(n):
    i = n
    for i in range(0, n-1):
        return i
        i +=1

arr = []
I got an a list [0], which is obvious, because the loop ended after return. But how can I rearrange the output() function to be able to append its output to a list arr? Thanks again!
You have wrong assumptions how for-loop works. I advise to use built-in help for getting basic understanding:

>>> help('for')
The "for" statement

The "for" statement is used to iterate over the elements of a sequence
(such as a string, tuple or list) or other iterable object:

   for_stmt ::= "for" target_list "in" expression_list ":" suite
                ["else" ":" suite]


The for-loop makes assignments to the variables(s) in the target list.
This overwrites all previous assignments to those variables including
those made in the suite of the for-loop:

   for i in range(10):
       i = 5             # this will not affect the for-loop
                         # because i will be overwritten with the next
                         # index in the range
/.../  # press Q to exit help
I'm not 'in'-sane. Indeed, I am so far 'out' of sane that you appear a tiny blip on the distant coast of sanity. Bucky Katt, Get Fuzzy

Da Bishop: There's a dead bishop on the landing. I don't know who keeps bringing them in here. ....but society is to blame.
(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!

Possibly Related Threads…
Thread Author Replies Views Last Post
  python prints none in function output chairmanme0wme0w 3 171 Jul-07-2021, 05:18 PM
Last Post: deanhystad
  print function output wrong with strings. mposwal 5 620 Feb-12-2021, 09:04 AM
Last Post: DPaul
  How to append multiple <class 'str'> into a single List ahmedwaqas92 2 578 Jan-07-2021, 08:17 AM
Last Post: ahmedwaqas92
  Output with none, print(x) in function Vidar567 3 496 Nov-24-2020, 05:40 PM
Last Post: deanhystad
  output correction using print() function afefDXCTN 2 2,410 Oct-13-2020, 12:58 PM
Last Post: cvilao
  Append list into list within a for loop rama27 2 781 Jul-21-2020, 04:49 AM
Last Post: deanhystad
  Append only adding the same list again and again viraj1123 4 721 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 771 Apr-22-2020, 01:01 PM
Last Post: deanhystad
  json.dumps list output qurr 12 1,898 Apr-08-2020, 10:13 PM
Last Post: micseydel
  If item in list = true, Output = xx kroh 0 605 Feb-19-2020, 09:17 AM
Last Post: kroh

Forum Jump:

User Panel Messages

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