-1

I have a variable "final" = lst1.append(num1) I want to print final, but when I do it prints "None", rather than the value I want.

Code:

lst1 = [1,2,3,4]
num1 = 7
final = lst1.append(num1)

print ("The value for final is",final)

Here, I want it to print "The value for final is [1,2,3,4,7]", but instead it's printing "The value for final is None." What am I doing wrong? Is the problem here, or might I be returning a value wrong elsewhere in my code? (This code is just an small example for the error).

Also, is there a way to make it so when printing final, instead of it being a list, it prints it as a string? So 12347 instead of [1,2,3,4,7]

Help is appreciated!

Lorena
  • 19
  • 1
  • 4

1 Answers1

0

lst.append(num1) doesn't create new list - it adds element directly to lst. So it doesn't have to return anything (so it returns None).

You need print(lst1)

To create final and keep original lst do

final = lst1 + [num1]

It adds two list (so I have to use [] with num1 to create second list) and assings it to final.

Or duplicate lst as final and append() to final

final = list[:]  # duplicate list
final.append(num1)

To print list of numbers you have to convert numbers to strings and concatenate it.

lst = [1,2,3,4]

txt = []

for x in lst:
    txt.append( str(x) )

print( "".join(txt) )

or shorter

print( "".join(str(x) for x in lst) )
furas
  • 134,197
  • 12
  • 106
  • 148
  • That works! Thanks. Could you possibly help me understand why lst1 is now equal to lst1.append(num1), even though it was done when defining the final variable? – Lorena Oct 09 '16 at 19:56
  • `lst1.append()` adds element directly to `lst1`. So it doesn't have to return value. If you want `final` and keep original `lst` (without `num1`) then use `final = lst1 + [num1]` It adds two lists and create new one which you assign to `final` – furas Oct 09 '16 at 20:01