Convert string list to list Python

The most Pythonic way to convert a list of strings to a list of ints is to use the list comprehension [int[x] for x in strings]. It iterates over all elements in the list and converts each list element x to an integer value using the int[x] built-in function.

This article shows you the simplest ways to convert a one-dimensional list consisting only of strings to a list of ints.

Problem: Given a list of strings ["1", "2", "-3"]. How to convert it to a list of ints [1, 2, -3]?

  • Problem Variant: Given a list of strings with mixed representations ["1", "2.0", "-3.4"]. How to convert it to a list of ints [1, 2, -3]?

We’ll dive into the easier base problem first and examine the problem variant in Method 5.

Method 1: List Comprehension

Suppose we have a list:

a = ["1", "2", "-3"]

Now, check the type of the first list element:

print[type[a[0]]] #

Let’s apply the built-in function int[], and get a list of integers using list comprehension:

a = ["1", "2", "-3"] print[[int[x] for x in a]] # [1, 2, -3]

List comprehension is a compact way of creating lists. The simple formula is [expression + context]. Expression: What to do with each list element? Context: What elements to select? The context consists of an arbitrary number of for and if statements.

You can watch me explain list comprehensions in this video:

Check the type of numbers in the new list:

A = [int[x] for x in a] print[type[A[0]]] #

The built-in function int[] converts a string to an integer. Thus, it helps us create a new list of ints from the list of strings in a single line of code.

Method 2: Map Function

The built-in function map is well optimized and efficient, when it is called, the elements of the list are retrieved upon access. Therefore, one element is stored and processed in memory, which allows the program not to store the entire list of elements in the system memory.

Apply to the same list a the following code:

a = ["1", "2", "-3"] print[list[map[int, a]]] # [1, 2, -3]

? The map[] function applies the first argument, a function, to each element in an iterable. It transforms each element in the original iterable to a new element and returns a new iterable map object of transformed values. To obtain a list, you need to convert it using the built-in list[] constructor.

You can watch my explainer video of the map function here:

Method 3: For Loop

Of course, you can also convert a list of strings to a list of ints using a simple for loop. This is what most people coming from a programming language such as Java and C++ would do as they don’t know the most Pythonic way of using list comprehension, yet [see Method 1].

a = ["1", "2", "-3"] ints = [] for element in a: ints.append[int[element]] print[ints] # [1, 2, -3]

This basic method to convert a list of strings to a list of integers uses three steps:

  • Create an empty list with ints = [].
  • Iterate over each string element using a for loop such as for element in list.
  • Convert the string to an integer using int[element] and append it to the new integer list using the list.append[] method.

Method 4: List Comprehension + eval[]

You can also use the eval[] function in a list comprehension to convert a list of strings to a list of ints:

a = ["1", "2", "-3"] ints = [eval[x] for x in a] print[ints] # [1, 2, -3]

Python’s built-in eval[s] function parses the string argument s into a Python expression, runs it, and returns the result of the expression. If the “expression” is a simple integer representation, Python converts the argument s to an integer.

You can watch me introducing the ins and outs of the eval[] function in this short guide:

Method 5: Mixed String Representation with Rounding

Problem Variant: Given a list of strings with mixed representations ["1", "2.0", "-3.4", "3.6"]. How to convert it to a list of ints [1, 2, -3, 4]?

The challenge is to convert each string to a float first and only then convert it to an integer. These two steps are integral and none can be skipped because you need the float to be capable of representing any number. But you also need the integer as this is the goal you set out to do: converting a list of strings to a list of ints.

❗ Convert a list of mixed string representations to a list of rounded integers this by chaining the built-in functions round[] and float[] in a list comprehension expression [round[float[s]] for s in a], assuming that the list of mixed string representation is stored in the variable a.

a = ["1", "2.0", "-3.4", "3.6"] ints = [round[float[s]] for s in a] print[ints] # [1, 2, -3, 4]

You can learn everything about the round[] function in the following video:

To boost your Python skills the easy way, feel free to join my free email academy with lots of free content and cheat sheets—if you haven’t already! 🙂

If you want to go all-in and learn Python while getting paid in the process, check out my Python freelancer course—the number one freelance developer education in the world!

While working as a researcher in distributed systems, Dr. Christian Mayer found his love for teaching computer science students.

To help students reach higher levels of Python success, he founded the programming education website Finxter.com. He’s author of the popular programming book Python One-Liners [NoStarch 2020], coauthor of the Coffee Break Python series of self-published books, computer science enthusiast, freelancer, and owner of one of the top 10 largest Python blogs worldwide.

His passions are writing, reading, and coding. But his greatest passion is to serve aspiring coders through Finxter and help them to boost their skills. You can join his free email academy here.

In this short tutorial, find how to convert string to list in Python. We look at all the ways you can achieve this along with their pros and cons.

Table of Contents - Convert string to list in Python

  • Converting string to list in Python
  • Solution 1: Using Split[]
  • Solution 2: Using list[]
  • Limitations and Caveats
  • Other Related Concepts

Converting string to list in Python:

Data type conversion or type casting in Python is a very common practice. However, converting string to list in Python is not as simple as converting an int to string or vice versa.

Strings can be converted to lists using list[] . We will look at this method below. However, in this method, Python would not know where each item starts and ends, returning a list of characters. Hence, Python provides a few alternate methods which can be used to convert a string to a list.

Solution 1: Using Split[]

The split method is used to split a string based on a specified delimiter. Once split, it returns the split string in a list, using this method we can convert string to list in Python.

Syntax:

string.split[ delimiter, maxsplit]

Parameters:

  • Delimiter - Optional. Specifies the desired delimiter to use when splitting the string. If left empty, whitespaces are considered delimiters.
  • Maxsplit - Optional. Specifies how many splits to do.

Code to Convert string to list in Python

str_1 = "Hire the top 1% freelance developers" list_1 = str_1.split[] print[list_1] #Output: #['Hire', 'the', 'top', '1%', 'freelance', 'developers']
Note: Since no argument was passed as a delimiter, the string was split on whitespace. Now let’s take a look at an instance where the delimiter is specified.str_1 = "Hire-the-top-1%-freelance-developers" list_1 = str_1.split["-"] print[list_1] #Output: #['Hire', 'the', 'top', '1%', 'freelance', 'developers']

Solution 2: Using list[]

As aforementioned, this method converts a string into a list of characters. Hence this method is not used quite often. I would recommend using this method only if you are certain that the list should contain each character as an item and if the string contains a set of characters or numbers that are not divided by a space. If not, the spaces would also be considered as a character and stored in a list.

Code to Convert string to list in Python:

str_1 = "Hire freelance developers" list_1 = list[str_1.strip[" "]] print[list_1] #Output: ['H', 'i', 'r', 'e', ' ', 'f', 'r', 'e', 'e', 'l', 'a', 'n', 'c', 'e', ' ', 'd', 'e', 'v', 'e', 'l', 'o', 'p', 'e', 'r', 's']

Convert string to list in Python - Closing thoughts

The split[] method is the recommended and most common method used to convert string to list in Python. This method does not have any significant cons. On the other hand, the typecast method is not widely recommended and is used only when the requirements are met. However, please feel free to practice both methods to facilitate a better understanding of the concept.

We continue with Flexiple's tutorial series to explain the code and concept behind common use cases. In this article ...

We continue with Flexiple's tutorial series to explain the code and concept behind common use cases. In this article ... 

Video liên quan

Chủ Đề