Appending to list - None result

大憨熊 提交于 2021-02-04 07:53:43

问题


Data:

lis_t = [['q', 'w', 'e'],['r', 't', 'y']]

Expected Outcome:

lis_t = [['q', 'w', 'e', 'u'],['r', 't', 'y']]

problem description: I am trying to append to the list above however not able to append the same as it somehow results in none. Please help me understand what am I doing wrong.

Code written:

lis_t = [['q', 'w', 'e'],['r', 't', 'y']]
lis_t[0] = lis_t[0].append('u')
print(lis_t[0])
print(lis_t)

output:

None
[None, ['r', 't', 'y']]

回答1:


lis_t[0].append('u') this returns None value and then you assigning this to lis_t[0] that's why you are getting None value

lis_t = [['q', 'w', 'e'],['r', 't', 'y']]
lis_t[0].append('u')
print(lis_t)



回答2:


do this

lis_t = [['q', 'w', 'e'],['r', 't', 'y']]
lis_t[0].append('u')
print(lis_t)



回答3:


Python function always return value when invoked. If no return value provided it will return None.

python list.append() is function which have no return value so it will be returning None when invoked.

what you are doing is assigning the list.append() method invocation to lis_t[0]

so the correct way in your case is.

lis_t[0].append('u')



回答4:


apart from

list_t[0].append('u')

you can do (if you like to use the '+')

list_t[0] += ['u']

or

list_t[0] = list_t[0] + ['u']

The result is always this

print(list_t[0])

>>> ['q', 'w', 'e', 'u']


来源:https://stackoverflow.com/questions/49144964/appending-to-list-none-result

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!