Why can I not replace the following first code:
def conversion7(x,k):
l=list(x)
l.append(k)
return tuple(l)
t=(1,2,3,4)
print(conversion7(t,7))
With the second one:
def conversion7(x,k):
return tuple(list(x).append(k))
t=(1,2,3,4)
print(conversion7(t,7))
The first code works. Here is the compiler output of the second code:
Traceback (most recent call last):
File "<string>", line 5, in <module>
File "<string>", line 2, in conversion7
TypeError: 'NoneType' object is not iterable
>
The purpose of the codes is to push a tuple by converting it to a list, pushing the list and then converting that back to a tuple.
CodePudding user response:
Since append does not return a reference to the list, as chepner has pointed out, you could do the following:
def conversion7(x,k):
return tuple(list(x) [k])
Or skip list conversion and immediately add tuples:
def conversion7(x,k):
return x (k,)