Home > front end >  Python extend function not working - not sure why
Python extend function not working - not sure why

Time:11-10

I have the following code where I want to add the string 'NSQscores' to the list of strings 'newlist'.

However, the following code gives me a 'none'.

columnlist = list(newdf.columns)
newlist = columnlist[0:87]
newlist2 = newlist.extend(['NSQscores'])
print(newlist2)

none

Would be so grateful if anybody could give me a helping hand!

As an example:

newlist[5:10]

['military-quantised',
 'mental_imagery-quantised',
 'navigate_growup-quantised',
 'independent_nav-quantised',
 'response-1 -quantised']

CodePudding user response:

x.extend modifies x in place and returns None. So you added an element to newlist and set newlist2 to None.

Try newlist2 = newlist ['NSQscores']. Or just use newlist instead of creating another one.

CodePudding user response:

.extend is a mutator, so it will modify newlist and not return anything. you can just do newlist.extend(["NSQscores"]) without assigning the output to anything

As a sidenote, you'd probably be better served with the .append method with something like this: newlist.append("NSQscores") if you're only adding single items. (It's still a mutator like extend, so it returns nothing, but designed specificially for adding a single value)

  • Related