Python Split List Tutorial

The list is one of the most popular types for the Python programming language. The splitting list or list items are regularly used for the operation. In this tutorial, we will learn how to split a string or items in a list.

String split() Syntax

String data type provides the split() mehtod which is used to split string. The split() method has the following syntax.

STRING.split(SEPARATOR,MAXSPLIT)
  • STRING is the string variable or data which will be splitted.
  • SEPARATOR is the separator carachter which will be splitted. This paramater is set whitespace. This parameter is optional.
  • MAXSPLIT specified how many splits to do. Default value is -1 which means all occurences. This parameter is optional.

In the following example we will split the variable named sentence which is a string. It has multiple words separated with whitespaces and we will use the default separator without specifying it. Also the maxsplit value will be used as default.

sentence = "I like the pythontect.com"

lst = sentence.split()

print(lst)

The output will be like below where every word is set as a list item.

['I', 'like', 'the', 'pythontect.com']

Another popular use case is provide the split characters in order to separate them into list items. In the following example we will use the comma as separator.

sentence = "I,like,the,pythontect.com"

lst = sentence.split(",")

print(lst)

The output is like below.

['I', 'like', 'the', 'pythontect.com']

Split List with Comprehension

List is used to store multiple items which can be string type. If the string items has some extra characters we want to remove of split we can use the string split() method. As an example is the items are like “name,surname” and we want to split the surname and only use the name we can use the list split with comprehension.

students=["ismail,baydan","ahmet,baydan","elif,baydan"]

student_names = [i.split(',')[0] for i in students]

print(student_names)

The output will be like below. The i.split(‘,’) will split the “ismail,baydan” into a list with two items and [0] will return the first items with index number 0 which is “ismail”.

['ismail', 'ahmet', 'elif']

Split List with for Loop and List append() Method

The list type can be enumarated with the for loop for each item and these items can be splitted with the split method and the append() method can be used to add splitted string into the new list.

students=["ismail,baydan","ahmet,baydan","elif,baydan"]

student_names=[]

for i in students:
   student_names.append(i.split(',')[0])

print(student_names)

The output will be like below.

['ismail', 'ahmet', 'elif']

Leave a Comment