0

To learn Python, I am referring 'Learning Python' by Mark Lutz. So, while going through its Chapter 20 (Comprehensions and Generators) it said that

Fundamental built in tools such as range, map, dictionary keys and files are now generators

I agree with statement for range, map and files, since, when I run following command I receive an 'Object' instead of complete data:

range(3)

returns

range(0,3)

and map(abs,[-1,-2,3,4])returns

<map object at 0x0000025B92164040>

However, when I type this:

d = {1:1,2:2}
d.keys()

I get: dict_keys([1, 2]) i.e. full list of keys in form of list.

So, if the d.keys() method displays all keys at once in form of list instead of returning an object like range and map, then how the method is referred to a Generator?

P.S.: I am using Python 3.7 and the book is probably written for a lower version

Anurag Gupta
  • 31
  • 1
  • 6
  • [What you're looking at is actually called a `view` & is not the same as a full list of keys](https://stackoverflow.com/questions/47273297/python-understanding-dictionary-view-objects) – PeptideWitch Nov 10 '21 at 04:25
  • 1
    As far as I can tell from a search, that book was last published in 2013. It is very out of date. At the time it was written, the implementation of dict keys had been changed to be a generator. Since then, it has changed again to be a different kind of object, called a view. – Karl Knechtel Nov 10 '21 at 04:32
  • If you want to know how it works in your version of Python, and be sure that you have information that is up to date for that version, you should look at [the documentation](https://docs.python.org/3/library/stdtypes.html#dict.keys). You can see documentation for older versions of Python by selecting a different version from the controls at the top of the page. – Karl Knechtel Nov 10 '21 at 04:33
  • "when I run following command I receive an 'Object' instead of complete data:" This claim makes no sense at all. **Everything** in Python is an "object" - including generators and views. The *textual representation of* a `dict_keys` object *shows you* the values, but "complete data" isn't a meaningful concept. – Karl Knechtel Nov 10 '21 at 04:38
  • My main concern is how to check if the given built in is a generator? I have checked with documentation and it includes map, filter, enumerate etc in generators. But still not sure about the keys method – Anurag Gupta Nov 11 '21 at 00:52

0 Answers0