Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is the difference between list and iterator in Python? [closed]

I am reading the book Think Python: How to think like a computer scientist, which says that in Python 3.x, dict([list of tuples]) returns an iterator instead of a list (as is the case in Python 2.7).

The book did not explain it any further, which has left me confused. In particular, I would like to know:

  1. How are iterators and lists different, and

  2. What is the advantage of returning an iterator over a list?

like image 934
Abhishek Mishra Avatar asked Sep 03 '14 21:09

Abhishek Mishra


People also ask

Is Python list an iterator?

Lists, tuples, dictionaries, and sets are all iterable objects. They are iterable containers which you can get an iterator from.

What is the difference between iterable and iterator in Python?

An Iterable is basically an object that any user can iterate over. An Iterator is also an object that helps a user in iterating over another object (that is iterable). We can generate an iterator when we pass the object to the iter() method. We use the __next__() method for iterating.

Is list iterable or iterator in Python?

For example, a list is iterable but a list is not an iterator. An iterator can be created from an iterable by using the function iter(). To make this possible, the class of an object needs either a method __iter__, which returns an iterator, or a __getitem__ method with sequential indexes starting with 0.

What is meant by iterator in Python?

An iterator in Python is an object that contains a countable number of elements that can be iterated upon. In simpler words, we can say that Iterators are objects that allow you to traverse through all the elements of a collection and return one element at a time.


4 Answers

First of all, your book is wrong (or you've misunderstood it):

>>> dict([(1, 2), (3, 4), (5, 6)]) {1: 2, 3: 4, 5: 6} 

As you can see, dict([list of tuples]) returns a dictionary in both Python 2.x and 3.x.

The fundamental difference between a list and an iterator is that a list contains a number of objects in a specific order - so you can, for instance, pull one of them out from somewhere in the middle:

>>> my_list = ['a', 'b', 'c', 'd', 'e', 'f', 'g'] >>> my_list ['a', 'b', 'c', 'd', 'e', 'f', 'g'] >>> my_list[3] 'd' 

... whereas an iterator yields a number of objects in a specific order, often creating them on the fly as requested:

>>> my_iter = iter(range(1000000000000)) >>> my_iter <range_iterator object at 0x7fa291c22600> >>> next(my_iter) 0 >>> next(my_iter) 1 >>> next(my_iter) 2 

I'm using next() here for demonstration purposes; in real code it's more common to iterate over an iterator with a for loop:

for x in my_iter:     # do something with x 

Notice the trade-off: a list of a trillion integers would use more memory than most machines have available, which makes the iterator much more efficient ... at the cost of not being able to ask for an object somewhere in the middle:

>>> my_iter[37104] Traceback (most recent call last):   File "<stdin>", line 1, in <module> TypeError: 'range_iterator' object is not subscriptable 
like image 95
Zero Piraeus Avatar answered Sep 23 '22 16:09

Zero Piraeus


A list is a data structure that holds a sequence of values. An iterator is an object that provides an interface to retrieve values one at a time, via the next function.

An iterable object is one that provides a __iter__ method, which is invoked when you pass an iterable to the iter function. You don't often need to do this explicitly; a for loop, for example, does it implicitly. A loop like

for x in [1,2,3]:     print x 

automatically invokes the list's __iter__ method. You can do so explicitly with

for x in iter([1,2,3]):     print x 

or even more explicitly with

for x in [1,2,3].__iter__():     print x 

One way to see the difference is to create two iterators from a single list.

l = [1, 2, 3, 4, 5] i1 = iter(l) i2 = iter(l) print next(i1)   # 1 print next(i1)   # 2 print next(i2)   # 1 again; i2 is separate from i1 print l          # [1, 2, 3, 4, 5]; l is unaffected by i1 or i2 
like image 35
chepner Avatar answered Sep 22 '22 16:09

chepner


The iterator is the mechanism by which you can iterate over a list or some other set of objects/values using for. A list implements an iterator. But you can also implement iterators that return number sequences, random strings, etc.

When you return an iterator, you are merely returning the iteration object; the receiving code doesn't know anything about the underlying container or generator algorithm.

Iterators are lazy; they only return the next element in the sequence or list when asked to do so. You can therefore implement infinite sequences with them.

Further Reading
Iterator Types
The for statement

like image 34
Robert Harvey Avatar answered Sep 24 '22 16:09

Robert Harvey


The Critical definitions here are :

  • List : Fully stored in memory, and it will also be an iterator - i.e. you can go from one element to the next.
  • Iterable : Any object which implements the Iterator protocol - i.e. allow you to go from one element to the next. It could use data stored in memory, it could be a file, or each step could be calculated.

Many things are iterables which aren't lists, all lists are iterables

like image 36
Tony Suffolk 66 Avatar answered Sep 22 '22 16:09

Tony Suffolk 66