Unable to append item in a list after slicing it python

Question:

list = [54, 44, 27, 79, 91, 41]

num_4 = list[4]
def fun_2():
    y = list[:2]
    z = y.append(num_4)
    print(z)
fun_2()

code above is giving me None output,
objective- first slice a list then append a integer to it.

Asked By: Diler Launda

||

Answers:

This is because z does not contain the list but the y does.

List is mutable in python, which means,

y = list[:2]
z = y.append(num_4)

the above code will add num_4 to y and append() function returns none hence z will contain none.

So print y not z

Answered By: Himanshu Kawale
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.