Difference between obj.split() and obj

Viewed 135

When I type this code:

phrase = 'I love my life'
phrase = phrase.split()
phrase.remove('I')
phrase

I got this result as expected:

['love', 'my', 'life']

However, when I try to make it more concise:

phrase = 'I love my life'
phrase.split().remove('I')
phrase

I have this unexpected result:

'I love my life'

It's strange, what is the difference between phrase = phrase.split() and this object phrase.split()? When we type type(phrase.split()), it's a list as well.

So what is the difference between them? I didn't understand the error, someone could explain to me?

2 Answers

str.split()

Return a list of the words in the string, using sep as the delimiter string. If maxsplit is given, at most maxsplit splits are done (thus, the list will have at most maxsplit+1 elements). If maxsplit is not specified or -1, then there is no limit on the number of splits (all possible splits are made)...

strings are immutable in python. the above taken from python docs.org. in the code below, first case:

phrase = 'I love my life'   
phrase = phrase.split()
phrase.remove('I')

at line 1: phrase a var name binded to string object with the value "I love my life".

at line 2: phrase a var name binded to a list object! he is no more pointing to the previous string, cos we have assign it to point to new py object.

at line 3 : list.remove() works on the same list, updating it if the object you want to remove are exist in the list.

code snippet 2

phrase = 'I love my life'
phrase.split().remove('I')

at line 1: phrase a var name binded to string object with the value "I love my life".

at line 2: since string are immutables, the interpreter do the work for you and get the job done, but the result of this expression was not assigned to any var name! if you want to get the same behavior you need to assign the result to phrase var name or pythonly speaking, rebinding the phrase var name.

see the links below for further reading

list.remove

str.split

First, phrase.split() itself does nothing because you didn't assign it to a variable. However, even if you did phrase = phrase.split().remove('I'), it still wouldn't work because the .remove('I') doesn't return anything to the variable phrase. Basically, .split() returns a list, only if you assign it to a variable and .remove('I') mutates the lists itself and return None if you assign that to a variable.

Related