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?
#1
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
        print(i)

output(10)

arr = []
arr.append(output(10))
However, my arr list is still empty. How can I fix it please? Thanks a lot!
Reply
#2
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.
Reply
#3
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

print(add_two_random_numbers())
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)
print(return_nothing())
Output:
5 3 2 (4, 4) None
Reply
#4
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 = []
arr.append(output(10)) 
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!
Reply
#5
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):
       print(i)
       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.
Reply
#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


Possibly Related Threads…
Thread Author Replies Views Last Post
  append str to list in dataclass flash77 6 343 Mar-14-2024, 06:26 PM
Last Post: flash77
  problem in output of a function akbarza 9 1,095 Sep-29-2023, 11:13 AM
Last Post: snippsat
Question How to append integers from file to list? Milan 8 1,360 Mar-11-2023, 10:59 PM
Last Post: DeaD_EyE
  How to print the output of a defined function bshoushtarian 4 1,236 Sep-08-2022, 01:44 PM
Last Post: deanhystad
  read a text file, find all integers, append to list oldtrafford 12 3,371 Aug-11-2022, 08:23 AM
Last Post: Pedroski55
  Using .append() with list vs dataframe Mark17 7 9,899 Jun-12-2022, 06:54 PM
Last Post: Mark17
  sum() list from SQLAlchemy output Personne 5 4,345 May-17-2022, 12:25 AM
Last Post: Personne
  output correction using print() function afefDXCTN 3 10,961 Sep-18-2021, 06:57 PM
Last Post: Sky_Mx
  python prints none in function output chairmanme0wme0w 3 2,157 Jul-07-2021, 05:18 PM
Last Post: deanhystad
  print function output wrong with strings. mposwal 5 3,045 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