Create an account


Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
[Tut] How to Convert a String List to an Integer List in Python

#1
How to Convert a String List to an Integer List in 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]))
# <class 'str'>

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]))
# <class 'int'>

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!

The post How to Convert a String List to an Integer List in Python first appeared on Finxter.



https://www.sickgaming.net/blog/2021/04/...in-python/
Reply



Possibly Related Threads…
Thread Author Replies Views Last Post
  [Tut] Python Regex to Return String Between Parentheses xSicKxBot 0 22 05-04-2021, 05:21 PM
Last Post: xSicKxBot
  [Tut] [Floyd’s Algorithm] How to Detect a Cycle in a Linked List in Python? xSicKxBot 0 22 05-03-2021, 03:55 PM
Last Post: xSicKxBot
  [Tut] Sorting a List Based on Values From Another List xSicKxBot 0 31 04-29-2021, 02:42 PM
Last Post: xSicKxBot
  [Tut] How To Apply A Function To Each Element Of A List? xSicKxBot 0 33 04-25-2021, 07:02 PM
Last Post: xSicKxBot
  [Tut] How To Check if One String is a Subsequence of Another? xSicKxBot 0 36 04-22-2021, 05:00 PM
Last Post: xSicKxBot
  [Tut] Converting Integer to String in Python xSicKxBot 0 39 04-18-2021, 11:56 AM
Last Post: xSicKxBot
  [Tut] How To Remove All Non-Alphabet Characters From A String? xSicKxBot 0 34 04-17-2021, 09:56 PM
Last Post: xSicKxBot
  [Tut] How to Check if a Python String Contains Only Digits? xSicKxBot 0 40 04-12-2021, 12:23 PM
Last Post: xSicKxBot
  [Tut] How to Convert a Float List to a String List in Python xSicKxBot 0 42 04-07-2021, 02:53 PM
Last Post: xSicKxBot
  [Tut] Python String to Float Conversion xSicKxBot 0 42 04-01-2021, 11:07 PM
Last Post: xSicKxBot

Forum Jump:

[-]
Active Threads
(Indie Deal) God Eater 3, DRAGON BALL, T...
Last Post: xSicKxBot
Today 10:20 AM
» Replies: 0
» Views: 6
Microsoft - Making remote and hybrid mee...
Last Post: xSicKxBot
Today 05:33 AM
» Replies: 0
» Views: 7
News - JAVA EDITION: SNAPSHOT 21W19A
Last Post: xSicKxBot
Today 05:31 AM
» Replies: 0
» Views: 7
News - Koei Tecmo’s Guzzler Joins Hamste...
Last Post: xSicKxBot
Today 05:30 AM
» Replies: 0
» Views: 8
News - Sega Looking To Release Brand New...
Last Post: xSicKxBot
Today 05:30 AM
» Replies: 0
» Views: 7
Xbox Wire - Xbox Spotlight: Mental Healt...
Last Post: xSicKxBot
Today 05:30 AM
» Replies: 0
» Views: 7
News - Live services push EA to $6.19 bi...
Last Post: xSicKxBot
Today 05:29 AM
» Replies: 0
» Views: 48
News - Blog: Improving the ‘About This G...
Last Post: xSicKxBot
Today 05:29 AM
» Replies: 0
» Views: 44
[Tut] How to Check the Pandas Version in...
Last Post: xSicKxBot
Yesterday 08:38 PM
» Replies: 0
» Views: 8
(Indie Deal) NBA 2K21, MY HERO ONE'S JUS...
Last Post: xSicKxBot
Yesterday 08:37 PM
» Replies: 0
» Views: 6

[-]
Twitter

Copyright © SickGaming.net 2012-2020