Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python: Why Does str.split() Return a list While str.partition() Returns a tuple?

Tags:

python

Comparing Python's str.split() with str.partition(), I see that they not only have different functions (split() tokenizes the whole string at each occurrence of the delimiter, while partition() just returns everything before and everything after the first delimiter occurrence), but that they also have different return types. That is, str.split() returns a list while str.partition() returns a tuple. This is significant since a list is mutable while a tuple is not. Is there any deliberate reason behind this choice in the API design, or is it "just the way things are." I am curious.

like image 213
sparc_spread Avatar asked Apr 04 '15 21:04

sparc_spread


People also ask

Does split return a list or tuple?

The split() method splits a string into a list. You can specify the separator, default separator is any whitespace.

Why does split return a list?

The split() breaks the string at the separator and returns a list of strings. If no separator is defined when you call upon the function, whitespace will be used by default.

What does STR split return in Python?

Description. Python string method split() returns a list of all the words in the string, using str as the separator (splits on all whitespace if left unspecified), optionally limiting the number of splits to num.

Does the split function return a list?

The split() method breaks up a string at the specified separator and returns a list of strings.


2 Answers

The key difference between those methods is that split() returns a variable number of results, and partition() returns a fixed number. Tuples are usually not used for APIs which return a variable number of items.

like image 51
yole Avatar answered Oct 16 '22 15:10

yole


@yole answer summarise the reasoning why partition() returns tuple. But there is a nice way to "exploit" that fact. I found below example in "Automate the boring stuff with Python".

   before, sep, after = 'Hello, world!'.partition(' ')
   print(before)
like image 2
blekione Avatar answered Oct 16 '22 13:10

blekione