Python: Remove all the values except integer values from a given array of mixed values
Python List: Exercise - 212 with Solution
Filter Integers from Mixed List
Write a Python program to remove all values except integer values from a given array of mixed values.
Sample Solution-1:
Python Code:
# Define a function called 'test' that filters a list to include only integer values.
def test(lst):
return [lst for lst in lst if isinstance(lst, int)]
# Create a list 'mixed_list' containing a mix of data types, including floats, integers, and strings.
mixed_list = [34.67, 12, -94.89, "Python", 0, "C#"]
# Print a message indicating the original list.
print("Original list:", mixed_list)
# Print a message indicating the purpose of the following lines of code.
print("After removing all the values except integer values from the said array of mixed values:")
# Call the 'test' function with 'mixed_list' and print the result, which contains only integer values.
print(test(mixed_list))
Sample Output:
Original list: [34.67, 12, -94.89, 'Python', 0, 'C#'] After removing all the values except integer values from the said array of mixed values: [12, 0]
Flowchart:
Sample Solution-2:
Python Code:
# Define a function called 'test' that filters a list to include only values of integer type.
def test(lst):
return [x for x in lst if type(x) == int]
# Create a list 'mixed_list' containing a mix of data types, including floats, integers, and strings.
mixed_list = [34.67, 12, -94.89, "Python", 0, "C#"]
# Print a message indicating the original list.
print("Original list:", mixed_list)
# Print a message indicating the purpose of the following lines of code.
print("After removing all the values except integer values from the said array of mixed values:")
# Call the 'test' function with 'mixed_list' and print the result, which contains only integer values.
print(test(mixed_list))
Sample Output:
Original list: [34.67, 12, -94.89, 'Python', 0, 'C#'] After removing all the values except integer values from the said array of mixed values: [12, 0]
Flowchart:
Python Code Editor:
Previous: Write a Python program to remove an element from a given list.
Next: Write a Python program to calculate the sum of two lowest negative numbers of a given array of integers.
What is the difficulty level of this exercise?
Test your Programming skills with w3resource's quiz.
It will be nice if you may share this link in any developer community or anywhere else, from where other developers may find this content. Thanks.
https://www.w3resource.com/python-exercises/list/python-data-type-list-exercise-212.php
- Weekly Trends and Language Statistics
- Weekly Trends and Language Statistics