-2
lst = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]

def allElementsSingleRow(lst):
    for i in lst:
        print(i, end= " ")

print(allElementsSingleRow(lst))

print(allElementsSingleRow(lst)) is always printing None. How can I fix my code to not print this?

KetZoomer
  • 2,701
  • 3
  • 15
  • 43
  • 3
    Function allElementsSingleRow returns None so that's why you're printing None at the end. Just use: `allElementsSingleRow(lst)` (i.e. without the print) – DarrylG Jul 25 '21 at 18:39
  • 3
    Does this answer your question? [Why is this printing 'None' in the output?](https://stackoverflow.com/questions/28812851/why-is-this-printing-none-in-the-output) – DarrylG Jul 25 '21 at 18:41
  • 1
    Python functions can return a single value. This means you need to decide what it means to "return all the elements of a list". One way to do that is to return a list of elements...but you're starting with a list of elements, so what do you actually want your function to do? – Mark Jul 25 '21 at 18:46

3 Answers3

1

You're printing the elements and not returning anything. Either don't print the output of the function, or use a generator function if you want to do something like this.

Not Printing the Output of the Function:

lst = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]

def allElementsSingleRow(lst):
    for i in lst:
        print(i, end= " ")

allElementsSingleRow(lst)

Using a generator

lst = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]

def allElementsSingleRow(lst):
    for i in lst:
        yield i

for element in allElementsSingleRow(lst):
    print(element, end=" ")
KetZoomer
  • 2,701
  • 3
  • 15
  • 43
0

A list already contains all of its elements, so if your function is just supposed to return all the elements in the list, as a new list, that's simply the copy function:

def allElementsSingleRow(lst):
    return lst.copy()

print(allElementsSingleRow(lst))  
# [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]

If your function is supposed to return all of the elements in the list as a single space-separated string, that's the join function:

def allElementsSingleRow(lst):
    return " ".join(lst)

print(allElementsSingleRow(lst))
# 1 2 3 4 5 6 7 8 9 10
Samwise
  • 68,105
  • 3
  • 30
  • 44
0

The problem is you are again printing while calling the function and that function returns None. So if we use print(allElementsSingleRow(lst)) it will also print None at the end You can just make the call to your function and it is done.

lst = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]

def allElementsSingleRow(lst):
    for i in lst:
        print(i, end= " ")

allElementsSingleRow(lst) # no need of print(allElementsSingleRow(lst))
Rohith V
  • 1,089
  • 1
  • 9
  • 23