0

Here is the following code that I have executed but the answer I desired should be like [1, 4, 6, 7] but instead the output is [False, True, True, True, False, False, True, False]... Please guide me on how can I get the desired output.

a_list = ["a", 1, 4, 6, "b", "d", 7, "o"]
result_list = [(type(x) == int) for x in a_list]
print(result_list)
ForceBru
  • 43,482
  • 10
  • 63
  • 98
MûHammad UMar
  • 131
  • 1
  • 10

3 Answers3

2

[(type(x) == int) for x in a_list] means: fill the list with the values of (type(x) == int) (which are booleans), where the elements x come from a_list. Thus, this list comprehension creates a list of booleans.

You want to get all the items of a_list that satisfy some criterion. So, use this:

[
  x # get all items of `a_list`...
  for x in a_list
  if isinstance(x, int) # ...that satisfy this
]

Here's why you should use isinstance(x, int) instead of type(x) == int: What are the differences between type() and isinstance()?.

ForceBru
  • 43,482
  • 10
  • 63
  • 98
2

you did well, the reason why print(result_list) returns boolean values is because its returning the result of the comparison done in type (x) == int.

In order to return the int values in the list, you need to say for x where x is the value in a_list, if its of type int, store that value in a new list. I named the result list for integers result_num_list See code snippet below:

a_list = ["a", 1, 4, 6, "b", "d", 7, "o"]
result_num_list = [x for x in a_list if type(x)==int]
print(result_num_list)

The output will be [1, 4, 6, 7]

Fruitymo
  • 33
  • 7
1

There is a long way of doing this and a short way: Short:

a_list = ["a", 1, 4, 6, "b", "d", 7, "o"]
result_list = [x for x in a_list if (type(x) == int)]
print(result_list)

Long (but easier to read):

a_list = ["a", 1, 4, 6, "b", "d", 7, "o"]
result_list = []
for i in a_list:
    if type(i) == int:
        result_list.append(i)
print(result_list)