Python - Convert CSV String to List


Convert CSV String to List

To convert a CSV (Comma Separated Value) string to a list of items in Python, call split() method on the CSV string, and pass comma character as the delimiter string.

The string split() method splits the given CSV string into values, and returns them as a list.

The syntax of the expression that returns a list of values, given a CSV string x is

x.split(',')

The elements of the returned list are of type string. We may convert them to other datatype as per requirements.

Examples

1. Convert CSV string to list of values

In the following example, we take a CSV string in x, and convert this string into a list of values.

Python Program

x = 'apple,banana,cherry'
output = x.split(',')
print(output)

Output

['apple', 'banana', 'cherry']

2. Convert CSV string to a list of integers

In the following example, we take a CSV string in x, where the values are integer numbers. We shall convert this string into a list of numbers using string split() method, int() builtin function, and list comprehension.

Python Program

x = '21,14,44,8,62'
#split string by comma
output = x.split(',')
#convert each element in list to int
output = [int(n) for n in output]
print(output)

Output

[21, 14, 44, 8, 62]

Summary

In this tutorial of Python Examples, we learned how to convert a CSV string to a list of values, with the help of examples.