Here is my code:
a = ['a','b','c','d','e']
b = a.remove('b')
print(a)
print(b)
It prints that b
is None
. I also want b
to be 'b'
.
CodePudding user response:
Python list remove() function doesn't return anything - it removes the item (if found) in situ
To achieve your objective:
['a','b','c','d','e']
b = 'b'
a.remove(b)
print(a)
print(b)
CodePudding user response:
Python's remove()
does not have a return value, so b
is always None
Take a look at this snippet:
>>> a = ['a','b','c','d','e']
>>> print(a)
['a', 'b', 'c', 'd', 'e']
>>> a.remove("b")
>>> print(a)
['a', 'c', 'd', 'e']
CodePudding user response:
remove()
removes the value from list but return None
. You might need pop()
.
a = ['a','b','c','d','e']
b = a.pop(a.index("b"))
print(a)
print(b)
Output:
['a', 'c', 'd', 'e']
b
CodePudding user response:
Variable Vs function
b = a.remove('b')
This is a variable, a variable will do an action and store the result returned. Your variable removes b from the list a so b stores nothing as remove is an action (function) but doesn't return anything. Therefor nothing is stored. So when you call b you get nothing.
If you changed b into a function, now whenever you use b() b will be removed perminetantly from the list a. So later if you add b again to the list you can use b() function to remove it again.
This example removes then adds back b when you use function b()
Code:
alphabet = ['a','b','c','d','e']
print(alphabet)
def b(): # this is a function
alphabet.remove('b') #removes 'b'
print(alphabet) #returns result to cons
alphabet.insert(1, 'b')#adds b back
return
b() #functions need to be called to work
print(alphabet)
Now whenever you call b() it will be your alphabet without the first letter b in it.
This is an over the top explanation but I hope this helps you understand python better.