After execution, we will get a list of integers as shown below. To convert a list of strings to a list of integers, we will pass the int() function as the first input argument to the map() function and the list of strings as the second input argument. It executes the function given in the input argument with all the elements of the input iterable object one by one and returns an iterable object with the output values. The map() function takes a function as its first input argument and an iterable object as the second input argument. The map() function is used to apply a function to all of the elements of an iterable object. List of Strings to List of Integers Using map() Function myList = įile "/home/aditya1117/PycharmProjects/pythonProject/string1.py", line 2, in Using the list comprehension has a restriction that we won’t be able to handle errors if any element of the input list is not converted to an integer because we cannot use exception handling inside the list comprehension syntax. Instead of the for loop, we can use list comprehension and the int() function to convert a list to strings to a list of integers as follows. The output list is: List of Strings to List of Integers Using List Comprehension Output: PFB cannot be converted to integer. Print(" cannot be converted to integer.".format(element)) You can observe this in the following example. In this way, we will get a list of integers using only those elements from the input list that can be directly converted to an integer using the int() function. In the except block, we will print each element that cannot be converted to an integer. Inside the for loop, we will convert the element to an integer using the int() function in the try block before appending it to the output_list. To handle the error, you can use exception handling in python using the try-except blocks. Due to this, the program raises the ValueError exception. Here, you can see that the string “PFB” could not be converted to an integer. ValueError: invalid literal for int() with base 10: 'PFB' Output: Traceback (most recent call last):įile "/home/aditya1117/PycharmProjects/pythonProject/string1.py", line 4, in If there are elements in the list that cannot be converted to an integer, the program will run into the ValueError exception as shown below. Print("The output list is:", output_list)
0 Comments
Leave a Reply. |
AuthorWrite something about yourself. No need to be fancy, just an overview. ArchivesCategories |