-1

I am writing a list comprehension. My goal is to get a list in return, but for some reason I'm getting a set, even though i'm doing a comprehension on a list. Currently I have code that looks like this:

filteredList = {obj.index for obj in myObjectList if filter(obj) == True}

When I check the type of 'myObjectList', it's a list, but when I check the type of 'filteredList', it's a set. Why is a comprehension done on a list giving me a set?

Primusa
  • 13,136
  • 3
  • 33
  • 53
  • 2
    The type of the object isn't determined by what you're iterating over, but rather by the brackets around the comprehension. You have `{}` and no `k: v` type of behavior so the interpreter thinks you're trying to do a set comprehension. Do `filteredList = [...]` to get a list. – Primusa Feb 10 '19 at 06:09
  • Possible duplicate of [One-line list comprehension: if-else variants](https://stackoverflow.com/questions/17321138/one-line-list-comprehension-if-else-variants) – Masoud Rahimi Feb 10 '19 at 06:13

2 Answers2

1

The result from a comprehension isn't based on the data type that you are performing the comprehension on. It has to do with how you set up the result of the comprehension. In this case you are using curly braces for your comprehension, so you are getting a set as a result.

Try this instead:

filteredList = [obj.index for obj in myObjectList if filter(obj) == True]

This puts the resultant obj.index's inside of a list (defined by [] brackets), instead of a set ({} brackets)

iz_
  • 15,923
  • 3
  • 25
  • 40
Slam9
  • 41
  • 1
  • 5
0

Using curly braces for your comprehension generates a set or dict. You should be using square braces instead: [obj.index for obj in ...]

Albert
  • 211
  • 1
  • 6