Quantcast
Channel: Planet Python
Viewing all articles
Browse latest Browse all 22464

Python for Beginners: Convert a List of Strings to Ints in Python

$
0
0

In python, we use lists to store different elements. In this article, we will discuss different ways to convert a list of strings to ints. We will also discuss how we can convert a list of lists of strings to ints in python.

The int() Function

The int() function takes a string or a floating-point literal as its input argument and returns an integer as shown below.

myStr = "11"
print("data type of {} is {}".format(myStr, type(myStr)))
myInt = int(myStr)
print("data type of {} is {}".format(myInt, type(myInt)))

Output:

data type of 11 is <class 'str'>
data type of 11 is <class 'int'>

If the input to the int() function cannot be converted to an integer, the program runs into a ValueError exception and terminates with the message “ValueError: invalid literal for int() with base 10”. You can observe this in the following example.

myStr = "Aditya"
print("data type of {} is {}".format(myStr, type(myStr)))
myInt = int(myStr)
print("data type of {} is {}".format(myInt, type(myInt)))

Output:

data type of Aditya is <class 'str'>
Traceback (most recent call last):
  File "/home/aditya1117/PycharmProjects/pythonProject/string12.py", line 3, in <module>
    myInt = int(myStr)
ValueError: invalid literal for int() with base 10: 'Aditya'

To avoid the exception, we can first check if the input can be converted to an integer or not. The floating-point numbers will always be converted to integers. However, the ValueError exception can occur when the input to the int() function is a string and consists of characters other than digits. So, to convert a string to an integer, we will first check if it consists of only digits or not. For this, we will use the isdigit() method.

The isdigit() Method

The isdigit() method, when invoked on a string, returns true if the string consists of only the decimal digits as shown below.

myStr = "11"
is_digit = myStr.isdigit()
print("{} consists of only digits:{}".format(myStr, is_digit))

Output:

11 consists of only digits:True

If the string contains any other character except decimal digits, the isdigit() method will return False. You can observe this in the following example.

myStr = "Aditya"
is_digit = myStr.isdigit()
print("{} consists of only digits:{}".format(myStr, is_digit))

Output:

Aditya consists of only digits:False

We can use the isdigit() method to avoid ValueError exceptions while converting a string to an integer. For this, we will first invoke the isdigit() method on the string. If it returns True, we will use the int() function to convert the string to an integer. Otherwise, we will say that the string cannot be converted to an integer. You can observe this in the following example.

myStr = "Aditya"
is_digit = myStr.isdigit()
if is_digit:
    myInt=int(myStr)
    print("The integer is:",myInt)
else:
    print("'{}' cannot be converted into integer.".format(myStr))

Output:

'Aditya' cannot be converted into integer.

Now that we have discussed the working of the int() function and the isdigit() method, let's now discuss different approaches to convert a list of strings to ints in python.

Convert a List of Strings to Ints Using for Loop in Python

To convert a list of strings to ints in python, we will use the following steps.

  • First, we will create an empty list named new_list to store the integers. 
  • After that, we will iterate over the list of strings using a for loop. 
  • While iteration, we will first check if the current string can be converted to int or not using the isdigit() method. 
  • If the string can be converted to an int, we will use the int() function to convert the string into an int. Otherwise, we will say that the current string cannot be converted into an integer.
  • After converting the string into an int, we will append it to the new_list using the append() method. The append() method when invoked on new_list, takes the newly created integer as its input argument and adds it to new_list.
  • Finally, we will move to the next string in the input list.

After execution of the for loop, we will get the list of ints in the new_list. You can observe this in the following example.

myList = ['1', '2', '23', '32', '12', '44', '34', '55', '46', '21']
new_list = []
for string in myList:
    is_digit = string.isdigit()
    if is_digit:
        myInt = int(string)
        new_list.append(myInt)
    else:
        print("'{}' cannot be converted into an integer.".format(string))
print("The list of strings is:")
print(myList)
print("The list of ints is:")
print(new_list)

Output:

The list of strings is:
['1', '2', '23', '32', '12', '44', '34', '55', '46', '21']
The list of ints is:
[1, 2, 23, 32, 12, 44, 34, 55, 46, 21]

Convert a List of Lists of Strings to Ints Using for Loop in Python

To convert a list of lists of strings to ints using for loop, int() function, and the isdigit() function, we will use the following steps.

  • First, we will create an empty list named new_list to store the output list of lists.
  • After that, we will iterate through the inner lists of the input list of lists using a for loop. 
  • Inside the for loop, we will create an empty list named temp_list to store the list of ints obtained from the inner lists.
  • Then, we will iterate over the elements of each inner list using another for loop.
  • While iterating the elements of the inner list, we will first check if the current string can be converted to int or not using the isdigit() method. 
  • If the string can be converted to an int, we will use the int() function to convert the string into an int. Otherwise, we will say that the current string cannot be converted into an integer. Then, we will move to the next string in the current inner list.
  • After converting all the strings of the current inner list into integers, we will also append them to the temp_list using the append() method.  
  • After iterating each internal loop, we will append the temp_list to the new_list using the append() method. Then, we will move to the next inner list in the list of lists.

After execution of the for loops, we will get the lists of lists containing the integer elements instead of strings as shown in the following example.

myList = [['1', '2', '23'], ['32', '12'], ['44', '34', '55', '46'], ['21', "Aditya"]]
print("The list of lists of strings is:")
print(myList)
new_list = []
for inner_list in myList:
    temp_list = []
    for element in inner_list:
        is_digit = element.isdigit()
        if is_digit:
            myInt = int(element)
            temp_list.append(myInt)
        else:
            print("'{}' cannot be converted into an integer.".format(element))
    new_list.append(temp_list)

print("The list of lists of ints is:")
print(new_list)

Output:

The list of lists of strings is:
[['1', '2', '23'], ['32', '12'], ['44', '34', '55', '46'], ['21', 'Aditya']]
'Aditya' cannot be converted into an integer.
The list of lists of ints is:
[[1, 2, 23], [32, 12], [44, 34, 55, 46], [21]]

In the above example, the string ‘Aditya’ cannot be converted into an int. Hence, it has been omitted from the output.

Convert a List of Strings to Integers Using List Comprehension

List comprehension in python is used to create new lists from existing container objects. You can use list comprehension instead of for loops to convert a list of strings to a list of ints as shown below.

myList = ['1', '2', '23', '32', '12', '44', '34', '55', '46', '21']
new_list = [int(element) for element in myList]
print("The list of strings is:")
print(myList)
print("The list of ints is:")
print(new_list)

Output:

The list of strings is:
['1', '2', '23', '32', '12', '44', '34', '55', '46', '21']
The list of ints is:
[1, 2, 23, 32, 12, 44, 34, 55, 46, 21]

This approach doesn’t check if the string can be converted into an int or not before calling the int() function. Therefore, it is possible that the program may run into the ValueError exception if we find an element in the list that cannot be converted into an integer. You can observe this in the following example.

myList = ['1', '2', '23', '32', '12', '44', '34', '55', '46', '21', "Aditya"]
new_list = [int(element) for element in myList]
print("The list of strings is:")
print(myList)
print("The list of ints is:")
print(new_list)

Output:

Traceback (most recent call last):
  File "/home/aditya1117/PycharmProjects/pythonProject/string12.py", line 2, in <module>
    new_list = [int(element) for element in myList]
  File "/home/aditya1117/PycharmProjects/pythonProject/string12.py", line 2, in <listcomp>
    new_list = [int(element) for element in myList]
ValueError: invalid literal for int() with base 10: 'Aditya'

In the above example, the string ‘Aditya‘ cannot be converted into an int. Due to this, the program runs into a ValueError exception.

Exceptions cause a program to terminate abruptly. It may result in loss of data or work done in your program.

To handle exceptions so that the program doesn’t terminate abruptly, you can use python try-except blocks as shown below.

myList = ['1', '2', '23', '32', '12', '44', '34', '55', '46', '21', "Aditya"]
print("The list of strings is:")
print(myList)
try:
    new_list = [int(element) for element in myList]
    print("The list of ints is:")
    print(new_list)
except ValueError:
    print("Some values in the input list can't be converted to int.")

Output:

The list of strings is:
['1', '2', '23', '32', '12', '44', '34', '55', '46', '21', 'Aditya']
Some values in the input list can't be converted to int.

Convert a List of Strings to Ints Using the map() Function

The map() function is used to apply a function to all the elements of a container object using a single python statement. It takes a function as its first input argument and a container object as its second input argument. After execution, it returns a map object that contains the output elements. 

To convert a list of strings to ints, we will first obtain the map object by passing the int function as its first input argument and the list of strings as its second argument. Once we obtain the map object, we will convert it into a list using the list() constructor. The list will contain all the elements as integers. You can observe this in the following example.

myList = ['1', '2', '23', '32', '12', '44', '34', '55', '46', '21']
new_list = list(map(int,myList))
print("The list of strings is:")
print(myList)
print("The list of ints is:")
print(new_list)

Output:

The list of strings is:
['1', '2', '23', '32', '12', '44', '34', '55', '46', '21']
The list of ints is:
[1, 2, 23, 32, 12, 44, 34, 55, 46, 21]

Again, this approach doesn’t check if the string can be converted into an int or not before calling the int() function. Therefore, it is possible that the program may run into the ValueError exception if we find an element in the list that cannot be converted into an integer. You can observe this in the following example.

myList = ['1', '2', '23', '32', '12', '44', '34', '55', '46', '21', "Aditya"]
new_list = list(map(int, myList))
print("The list of strings is:")
print(myList)
print("The list of ints is:")
print(new_list)

Output:

Traceback (most recent call last):
  File "/home/aditya1117/PycharmProjects/pythonProject/string12.py", line 2, in <module>
    new_list = list(map(int, myList))
ValueError: invalid literal for int() with base 10: 'Aditya'

 To handle exceptions so that the program doesn’t terminate abruptly, you can use python try-except blocks as shown below.

myList = ['1', '2', '23', '32', '12', '44', '34', '55', '46', '21', "Aditya"]
print("The list of strings is:")
print(myList)
try:
    new_list = list(map(int, myList))
    print("The list of ints is:")
    print(new_list)
except ValueError:
    print("Some values in the input list couldn't be converted to int.")

Output:

The list of strings is:
['1', '2', '23', '32', '12', '44', '34', '55', '46', '21', 'Aditya']
Some values in the input list couldn't be converted to int.

Convert a List of Lists of Strings to Ints Using the map() Function

To convert a list of lists of strings to ints using the map() function in python, we will use the following steps.

  • First, we will create an empty list named new_list to store the output list. 
  • After that, we will iterate through the list of lists using a for loop.
  • During iteration, we will first obtain the map object of each inner list by passing the int function as its first input argument and the inner list of strings as its second argument. 
  • Once we obtain the map object, we will convert it into a list using the list() constructor.
  • The list will contain the elements of the inner list in integer form. We will append this list to the new_list using the append() method. Then, we will move to the next inner list.

After executing the for loop, we will get the list of lists containing integers as the elements of the inner lists as shown in the following code.

myList = [['1', '2', '23'], ['32', '12'], ['44', '34', '55', '46'], ['21']]
print("The list of lists of strings is:")
print(myList)
new_list = []
for inner_list in myList:
    temp_list = list(map(int, inner_list))
    new_list.append(temp_list)

print("The list of lists of ints is:")
print(new_list)

Output:

The list of lists of strings is:
[['1', '2', '23'], ['32', '12'], ['44', '34', '55', '46'], ['21']]
The list of lists of ints is:
[[1, 2, 23], [32, 12], [44, 34, 55, 46], [21]]

Again, the program may run to the ValueError exception in this case. So, don’t forget to use try-except blocks in the program as shown below.

myList = [['1', '2', '23'], ['32', '12'], ['44', '34', '55', '46'], ['21']]
print("The list of lists of strings is:")
print(myList)
new_list = []
for inner_list in myList:
    try:
        temp_list = list(map(int, inner_list))
        new_list.append(temp_list)
    except ValueError:
        print("Some values couldn't be converted to int.")

print("The list of lists of ints is:")
print(new_list)

Output:

The list of lists of strings is:
[['1', '2', '23'], ['32', '12'], ['44', '34', '55', '46'], ['21']]
The list of lists of ints is:
[[1, 2, 23], [32, 12], [44, 34, 55, 46], [21]]

Convert a List of Strings to Ints Using the eval() Function

The eval() function is used to parse and evaluate a python statement. The eval() function takes a string as its input argument, parses the string, evaluates the values, and returns the output.

For instance, we can pass the string “2+2” to the eval function and it will return 4 as output. You can observe this in the following example.

x = eval('2+2')
print(x)

Output:

4

Similarly, when we pass a string containing only decimal digits to the eval() function, it returns an integer as shown below.

x = eval('11')
print(x)

Output:

11

If the input string contains alphabetical characters other than numbers, the program will run into a NameError exception. You can observe this in the following example.

x = eval('Aditya')
print(x)

Output:

Traceback (most recent call last):
  File "/home/aditya1117/PycharmProjects/pythonProject/string12.py", line 1, in <module>
    x = eval('Aditya')
  File "<string>", line 1, in <module>
NameError: name 'Aditya' is not defined

Here, the term ‘Aditya‘ is evaluated as a variable name. Hence, the eval() function tries to obtain the value of the object associated with the variable ‘Aditya‘. However, the program doesn’t contain any variable named ‘Aditya‘. Hence, the program runs into a NameError exception.

To convert a list of strings to ints using the eval() function, we will use the following steps.

  • First, we will create an empty list named new_list to store the integers. 
  • After that, we will iterate over the list of strings using a for loop. 
  • While iteration, we will first check if the current string can be converted to int or not using the isdigit() method. 
  • If the string can be converted to an int, we will use the eval() function to convert the string into an int. Otherwise, we will say that the current string cannot be converted into an integer.
  • After converting the string into int, we will append it to the new_list using the append() method. 
  • Finally, we will move to the next string in the input list.

After execution of the for loop, we will get the list of ints in the new_list. You can observe this in the following example.

myList = ['1', '2', '23', '32', '12', '44', '34', '55', '46', '21', "Aditya"]
print("The list of strings is:")
print(myList)
new_list = []
for string in myList:
    is_digit = string.isdigit()
    if is_digit:
        myInt = eval(string)
        new_list.append(myInt)
    else:
        print("'{}' cannot be converted into int.".format(string))
print("The list of ints is:")
print(new_list)

Output:

The list of strings is:
['1', '2', '23', '32', '12', '44', '34', '55', '46', '21', 'Aditya']
'Aditya' cannot be converted into int.
The list of ints is:
[1, 2, 23, 32, 12, 44, 34, 55, 46, 21]

Convert a List of Lists of Strings to Ints Using the eval() Function

To convert a list of lists of strings to ints using the eval() function, we will use the following steps.

  • First, we will create an empty list named new_list to store the output list of lists.
  • After that, we will iterate through the inner lists of the input list of lists using a for loop. 
  • Inside the for loop, we will create an empty list named temp_list to store the int values obtained from the inner lists.
  • Then, we will iterate over the elements of the current inner list using another for loop.
  • While iterating the elements of the inner list, we will first check if the current string can be converted to int or not using the isdigit() method. 
  • If the string can be converted to an int, we will use the eval() function to convert the string into an int. Otherwise, we will say that the current string cannot be converted into an integer. Finally, we will move to the next string in the current inner list.
  • After converting all the strings of the current inner list into integers, we will append them to the temp_list using the append() method.  
  • After iterating each internal loop, we will append the temp_list to the new_list using the append() method. Then, we will move to the next inner list in the list of lists.

After execution of the for loops, we will get the lists of lists containing the integer elements instead of strings as shown in the following example.

myList = [['1', '2', '23'], ['32', '12'], ['44', '34', '55', '46'], ['21', "Aditya"]]
print("The list of lists of strings is:")
print(myList)
new_list = []
for inner_list in myList:
    temp_list = []
    for element in inner_list:
        is_digit = element.isdigit()
        if is_digit:
            myInt = eval(element)
            temp_list.append(myInt)
        else:
            print("'{}' cannot be converted into an integer.".format(element))
    new_list.append(temp_list)

print("The list of lists of ints is:")
print(new_list)

Output:

The list of lists of strings is:
[['1', '2', '23'], ['32', '12'], ['44', '34', '55', '46'], ['21', 'Aditya']]
'Aditya' cannot be converted into an integer.
The list of lists of ints is:
[[1, 2, 23], [32, 12], [44, 34, 55, 46], [21]]

Convert a List of Strings to Ints Inplace in Python 

All of the approaches discussed in the previous sections create a new output list. Instead of creating a new output list, if we want to convert the elements of the input list from string to int, we can do so using the int() method or the eval() method. 

Convert a List of Strings to Ints Inplace Using the int() Function

To convert a list of strings to ints inplace using the int() function, we will use the following steps.

  • First, we will find the length of the list of strings using the len() function. The len() function takes the list as its input argument and returns the length of the list. We will store the length in the variable list_len
  • After obtaining the length of the list, we will create a sequence of numbers from 0 to list_len using the range() function. The range() function takes list_len as the input argument and returns the sequence.
  • After obtaining the sequence, we will iterate through the sequence using a for loop. While iteration, we will access each element of the list using its index. 
  • After obtaining the element, we will check if it can be converted to an integer. For this, we will use the isdigit() method. 
  • If the string can be converted to an int, we will use the int() function to convert the string into an int. Otherwise, we will say that the current string cannot be converted into an integer. Finally, we will move to the next string in the current inner list.
  • After converting all the strings of the current inner list into integers, we will reassign them to their original place in the input list. 

After execution of the for loop, all the elements of the input list will be converted to integers. You can observe this in the following example.

myList = ['1', '2', '23', '32', '12', '44', '34', '55', '46', '21', "Aditya"]
list_len = len(myList)
sequence = range(list_len)
print("The list of strings is:")
print(myList)
for index in sequence:
    string = myList[index]
    is_digit = string.isdigit()
    if is_digit:
        myInt = int(string)
        myList[index] = myInt
    else:
        myList.remove(string)
        print("'{}' cannot be converted into int.".format(string))
print("The list of ints is:")
print(myList)

Output:

The list of strings is:
['1', '2', '23', '32', '12', '44', '34', '55', '46', '21', 'Aditya']
'Aditya' cannot be converted into int.
The list of ints is:
[1, 2, 23, 32, 12, 44, 34, 55, 46, 21]

In the above example, the string ‘Aditya’ cannot be converted to an integer. Therefore, we have removed the string using the remove() method.

Convert a List of Strings to Ints Inplace Using eval() Function

Instead of using the int() function, you can also use the eval() function to convert a list of strings to ints as shown below.

myList = ['1', '2', '23', '32', '12', '44', '34', '55', '46', '21', "Aditya"]
list_len = len(myList)
sequence = range(list_len)
print("The list of strings is:")
print(myList)
for index in sequence:
    string = myList[index]
    is_digit = string.isdigit()
    if is_digit:
        myInt = eval(string)
        myList[index] = myInt
    else:
        myList.remove(string)
        print("'{}' cannot be converted into int.".format(string))
print("The list of ints is:")
print(myList)

Output:

The list of strings is:
['1', '2', '23', '32', '12', '44', '34', '55', '46', '21', 'Aditya']
'Aditya' cannot be converted into int.
The list of ints is:
[1, 2, 23, 32, 12, 44, 34, 55, 46, 21]

Convert a List of Lists of Strings to Ints Inplace in Python

Convert a List of Lists of Strings to Ints Inplace Using int() Function

We can also convert a list of lists of strings to ints inplace using the int() function. For this, we will use the following steps.

  • We will iterate over the inner lists of the list of lists using a for loop.
  • For each inner list, we will find the length of the inner list of strings using the len() function. We will store the length in the variable list_len
  • After obtaining the length of the inner list, we will create a sequence of numbers from 0 to list_len using the range() function. The range() function takes list_len as the input argument and returns the sequence.
  • After obtaining the sequence, we will iterate through the sequence using a for loop. While iteration, we will access each element of the inner list using its index. 
  • After obtaining the element, we will check if it can be converted to an integer. For this, we will use the isdigit() method. 
  • If the string can be converted to an int, we will use the int() function to convert the string into an int. Otherwise, we will say that the current string cannot be converted into an integer. Finally, we will move to the next string in the current inner list.
  • After converting all the strings of the current inner list into integers, we will reassign them to their original place in the input inner list.

After execution of the above steps, the elements of the original list of lists will be converted into integers. You can observe this in the following example.

myList = [['1', '2', '23'], ['32', '12'], ['44', '34', '55', '46'], ['21', "Aditya"]]
print("The list of lists of strings is:")
print(myList)
for inner_list in myList:
    list_len = len(inner_list)
    sequence = range(list_len)
    for index in sequence:
        string = inner_list[index]
        is_digit = string.isdigit()
        if is_digit:
            myInt = int(string)
            inner_list[index] = myInt
        else:
            print("'{}' cannot be converted into int.".format(string))
            inner_list.remove(string)

print("The list of lists of ints is:")
print(myList)

Output:

The list of lists of strings is:
[['1', '2', '23'], ['32', '12'], ['44', '34', '55', '46'], ['21', 'Aditya']]
'Aditya' cannot be converted into int.
The list of lists of ints is:
[[1, 2, 23], [32, 12], [44, 34, 55, 46], [21]]

Convert a List of Lists of Strings to Ints Inplace Using eval() Function

Instead of using the int() function, you can also use the eval() function to convert a list of lists of strings to ints inplace as shown below. 

myList = [['1', '2', '23'], ['32', '12'], ['44', '34', '55', '46'], ['21', "Aditya"]]
print("The list of lists of strings is:")
print(myList)
for inner_list in myList:
    list_len = len(inner_list)
    sequence = range(list_len)
    for index in sequence:
        string = inner_list[index]
        is_digit = string.isdigit()
        if is_digit:
            myInt = eval(string)
            inner_list[index] = myInt
        else:
            print("'{}' cannot be converted into int.".format(string))
            inner_list.remove(string)

print("The list of lists of ints is:")
print(myList)

Output:

The list of lists of strings is:
[['1', '2', '23'], ['32', '12'], ['44', '34', '55', '46'], ['21', 'Aditya']]
'Aditya' cannot be converted into int.
The list of lists of ints is:
[[1, 2, 23], [32, 12], [44, 34, 55, 46], [21]]

Conclusion

In this article, we have discussed different ways to convert a list of strings to ints in python. If you need to convert a list of strings to ints, you can use the approach using the map() function. If you need to convert the list of strings to ints in place, you can use the approach discussed in the last two sections of the article.

I hope you enjoyed reading this article. To learn more about python programming, you can read this article on how to remove all occurrences of a character in a list in Python. You might also like this article on how to check if a python string contains a number.

Happy Learning!

The post Convert a List of Strings to Ints in Python appeared first on PythonForBeginners.com.


Viewing all articles
Browse latest Browse all 22464

Trending Articles



<script src="https://jsc.adskeeper.com/r/s/rssing.com.1596347.js" async> </script>