Why `print(colors = color.insert(0, "yellow")` return None?

Hello try to learn python here i have question about insert() method in list:

color = ["red", "blue", "green"]
print(color)

color[2] = "purple"
print(color)

color.insert(0, "yellow")
print(color)

colors = color.insert(0, "yellow")
print(colors)

output

['red', 'blue', 'green']
['red', 'blue', 'purple']
['yellow', 'red', 'blue', 'purple']
None

Why the last print() return None and not ['yellow', 'red', 'blue', 'purple']
Thanks in advance,

Regards,
gunungpw

colors has been assigned the value None because that’s what insert returns - inserting into a list modifies that list “in place”. Therefore, that method returns None rather than a list containing the new value.

Thankyou @ndc86430,
Sorry I still don’t understand, what you mean by “in place”? (english is not my first language)
if I understand insert() not return the list but None so i need to read more about what method/function return will be,

regard,
gunungpw

Functions that do something with objects can either modify the existing object (such functions are said to work “in place”), or create a modified copy of the original object while leaving the original unchanged.

For example, consider list sorting in Python:

>>> original_list = [1, 3, 2]
>>> sorted(original_list)  # `sorted` returns a new list.
[1, 2, 3]
>>> original_list  # The original list is unchanged.
[1, 3, 2]
>>> original_list.sort()
>>> # Note the lack of output.
>>> # `list.sort()` returns nothing, instead it modifies the original list.
>>> original_list
[1, 2, 3]

sorted is a copy-modify-return type function, while list.sort is a modify-in-place type function.

If we try to print the output of a function that returns nothing, None is printed:

>>> print(original_list.sort())
None

None is used in Python to conceptualize something that does not exist.

2 Likes

Thank you @abessman I understand now,
Hope you have a nice day