Print command writing in one line

Question:

I am learning Python and have a question about the print command.

Why in the following case the code with print command works in one line:

text = "The vegetables are in the fridge."
print(text.replace("vegetables", "fruits"))

but here when I write like this, I get no result ?

numbers = [12, 34, 23, 88, 1, 65]
fruits = ["apple", "pear", "orange", "grapes", "mango"]
print(fruits.extend(numbers))

Correct way is the following:

numbers = [12, 34, 23, 88, 1, 65]
fruits = ["apple", "pear", "orange", "grapes", "mango"]
fruits.extend(numbers)
print(fruits)

I mean, if the logic is the following that at first one function works and then the second, then why in the first one it just works?

I hope I could explain it.

Thanks beforehand,

Lilith

Asked By: Amaterasu

||

Answers:

.extend(...) returns None. Any method which mutates object in-place returns None.

.replace(...) returns a new string with replaced values.

But you can try this one-liner.

print(fruits.extend(numbers) or fruits)
#['apple', 'pear', 'orange', 'grapes', 'mango', 12, 34, 23, 88, 1, 65]

Docs say :

enter image description here

Answered By: Ch3steR
>>>fruits.extend(numbers)
None

This will change the fruits
But the new value does not return

Answered By: Nima

Python strings are immutable objects, which means that methods that are performed on them return new strings.

lists on the other hand are mutable, which means you can change them: add items to the list, change specific items in the list etc. These kind of changes are done in place: the same list is changed.

Usually, methods that are done in place do not have a return value. fruits.extend(numbers) has no return value because it changes fruits in place.

If you need to use fruits afterwards your solution of splitting it into two lines is good. If not, you can create a new list and print it as follows:

numbers = [12, 34, 23, 88, 1, 65]
fruits = ["apple", "pear", "orange", "grapes", "mango"]
print(fruits + numbers)
Answered By: ishefi

Here is what you think it is doing:

def extfruits(l1, l2):
    l3 = l1 + l2
    return l3
print(extfruits(fruits, numbers))

When in reality, it is printing the Method, which is just changing the value of fruits in place. So, you get None.

Answered By: Tatton Chantry