In python, why can't I use the extend function inside the print function?

Question:

If I write my code like this,

friends = ["Kafi", "Saif", "Shaheer", "Azmain", "Labid", "Faiz", "Azmain"]

lucky_numbers = [114, 151, 172, 7, 1, 63, 14, 543]

friends.extend(lucky_numbers)

print(friends)

then my code runs perfectly. But if I use the extend function inside the print function like this,

friends = ["Kafi", "Saif", "Shaheer", "Azmain", "Labid", "Faiz", "Azmain"]

lucky_numbers = [114, 151, 172, 7, 1, 63, 14, 543]

print(friends.extend(lucky_numbers))

then I get “None” as an output. Why can’t I use the extend function inside the print function?

Asked By: tryingtobeastoic

||

Answers:

extend is in-place function that returns nothing.
Printing output from a function that hasn’t returned anything will give you None
if you don’t want to change friends then make a copy of it

newfriends = friends.copy()
newfriends.extend(lucky_numbers)
print(newfriends)
Answered By: Kuldeep Singh Sidhu

Your print statement prints the return of friends.extend(lucky_numbers), which is None.
From the docs:

array.extend(iterable)
Append items from iterable to the end of the array.

So extend() changes the array it is called on, but it doesnt return anything, ergo there is nothing to print.

Answered By: Chrissu
Categories: questions Tags: , , ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.