2

I came across certain built-in functions such as zip and map.

I tried printing these functions, they resulted as zip object at 0x1007a06c8 or <map object at 0x003AB2E0>.

I understand that these functions return iterators, but I can also use a for loop to run through strings/lists/dicts as iterators. Thus, how are zip and map different, and how I am able to show them? What are some other examples that I should be aware of?

ngong123
  • 63
  • 5
  • Those are lazy iterators - they are only evaluated when iterated through. – rdas Jun 13 '20 at 09:28
  • 2
    There is a difference between `iterables` and `iterator objects` – Sayandip Dutta Jun 13 '20 at 09:29
  • So what's the relationship between an iterable and iterator object? Did a bit a searching and found that iterators can be classified as an iterable but not the other way around. For loops can run strings/dicts/lists/sets, but I believe so can iter()? – ngong123 Jun 13 '20 at 09:50

2 Answers2

2

Do something like:

list(zip(a,b))

Explanation:

The zip() function in Python 3 returns an iterator.

The purpose of this is to save memory by only generating the elements of the iterator as you need them, rather than putting it all into memory at once.

You can exhaust it once by doing list(zip(a,b)). So after that anytime you do list(zip(a,b)) would only result in empty list.

Mayank Porwal
  • 33,470
  • 8
  • 37
  • 58
1

zip, map and also range are no collections like lists, strings, sets or dicts, because they are evaluated lazily. This means, that they do not explicitly contain all the values, but only generate the next value when asked to do that (e.g. in a loop or when unpacked in a list).

So lists and maps are iterable, because you can iterate over them, but maps are generators, while lists are containers.

You can unpack generators to a list with list(map(...)) (also works sets or tuples and others), or use the asterisk (*) to unpack them to individual arguments of a function (print(*map(...))).

Niklas Mertsch
  • 1,399
  • 12
  • 24