{ }codelper

Reference › Python

Python split(): Split a String into a List

split() cuts a string every time the separator appears and returns a list. The original string is not changed. It is used most often to read input that has several values on one line.

string.split(sep=None, maxsplit=-1)

Splitting on whitespace

If you give no separator, spaces, tabs and newlines all count as separators. Several spaces in a row count as one, and spaces at the start and end are thrown away.

line = "  apple   banana cherry "words = line.split()print(words)print(len(words))
Output
['apple', 'banana', 'cherry']
3

Edit and run it →

Splitting on a separator such as a comma

If you give a separator, the string is cut only where exactly that text appears. The separator can be two or more characters long.

print("2026-11-24".split("-"))print("a, b, c".split(", "))print("a,,b".split(","))
Output
['2026', '11', '24']
['a', 'b', 'c']
['a', '', 'b']

Edit and run it →

When separators sit next to each other, as in the last line, the empty string between them becomes an item too. This is different from splitting with no separator.

Limiting the number of splits

The second argument is the maximum number of splits. The string is cut that many times from the front, and the rest is left as one piece. To cut from the back, use rsplit.

log = "ERROR disk full on /dev/sda"level, message = log.split(" ", 1)print(level)print(message)print("a.b.c".rsplit(".", 1))
Output
ERROR
disk full on /dev/sda
['a.b', 'c']

Edit and run it →

Reading one line of input as several numbers

What split() returns is a list of strings. To calculate with them as numbers, convert them one by one with map(int, ...).

a, b = map(int, input().split())nums = list(map(int, input().split()))print(a + b)print(sum(nums))
Input
3 4
10 20 30
Output
7
60

Edit and run it →

Common mistakes

split() and split(" ") are different

print("a  b".split())
print("a  b".split(" "))

→ ['a', 'b'] and ['a', '', 'b']

split(" ") cuts at every single space, so two spaces in a row leave an empty string in between. To split into words, use split() with no argument.

Calculating with the split result right away

a, b = input().split()
print(a + b)

→ With the input 3 4 you get 34, not 7

The pieces are strings, so + joins them together. Convert them to numbers, as in a, b = map(int, input().split()).

Unpacking into several variables when the count doesn't match

a, b = "1 2 3".split()

→ ValueError: too many values to unpack (expected 2)

The number of variables on the left must equal the number of pieces. If you don't know the count, store them in a single list, or collect the rest as in first, *rest = s.split().

Practice problems

See also