Questions tagged [iterator]

An iterator is an object-oriented programming pattern that allows traversal through a collection, agnostic of the actual implementation or object addresses in physical memory. It is one of the Gang of Four's behavioral design patterns.

8758
votes
41answers
1.9m views

What does the “yield” keyword do?

What is the use of the yield keyword in Python? What does it do?For example, I'm trying to understand this code1:def _get_child_candidates(self, distance, min_dist, max_dist):if self....
456
votes
4answers
96k views

Iterator invalidation rules

What are the iterator invalidation rules for C++ containers?Preferably in a summary list format.(Note: This is meant to be an entry to Stack Overflow's C++ FAQ. If you want to critique the idea of ...
601
votes
7answers
441k views

How to iterate through two lists in parallel?

I have two iterables in Python, and I want to go over them in pairs:foo=(1, 2, 3)bar=(4, 5, 6)for (f, b) in some_iterator(foo, bar):print "f: ", f, "; b: ", bIt should result in:f: 1;...
330
votes
12answers
235k views

What exactly are iterator, iterable, and iteration?

What are the most basic definitions of "iterable", "iterator" and "iteration in Python?I've read multiple definitions but their exact meaning still won't sink in.Can someone please help me with ...
484
votes
9answers
301k views

Build a Basic Python Iterator

How would one create an iterative function (or iterator object) in python?
49
votes
7answers
71k views

Modifying list while iterating [duplicate]

l=range(100) for i in l: print i, print l.pop(0), print l.pop(0)The above python code ...
531
votes
11answers
365k views

Calling remove in foreach loop in Java [duplicate]

In Java, is it legal to call remove on a collection when iterating through the collection using a foreach loop? For instance:List<String> names=....for (String name : names) {// Do ...
284
votes
10answers
331k views

How to avoid “ConcurrentModificationException” while removing elements from `ArrayList` while iterating it? [duplicate]

I'm trying to remove some elements from an ArrayList while iterating it like this:for (String str : myArrayList) {if (someCondition) {myArrayList.remove(str);}}Of course, I get ...
401
votes
8answers
104k views

Difference between Python's Generators and Iterators

What is the difference between iterators and generators? Some examples for when you would use each case would be helpful.
85
votes
6answers
23k views

How does zip(*[iter(s)]*n) work in Python?

s=[1,2,3,4,5,6,7,8,9]n=3zip(*[iter(s)]*n) # returns [(1,2,3),(4,5,6),(7,8,9)]How does zip(*[iter(s)]*n) work? What would it look like if it was written with more verbose code?
210
votes
13answers
105k views

Get the first item from an iterable that matches a condition

I would like to get the first item from a list matching a condition. It's important that the resulting method not process the entire list, which could be quite large. For example, the following ...
129
votes
3answers
77k views

What happens if you call erase() on a map element while iterating from begin to end?

In the following code I loop through a map and test if an element needs to be erased. Is it safe to erase the element and keep iterating or do I need to collect the keys in another container and do a ...
209
votes
25answers
61k views

Why use iterators instead of array indices?

Take the following two lines of code:for (int i=0; i < some_vector.size(); i++){//do stuff}And this:for (some_iterator=some_vector.begin(); some_iterator !=some_vector.end();...
15
votes
2answers
23k views

ConcurrentModificationException despite using synchronized

public synchronized X getAnotherX(){ if(iterator.hasNext()){X b=iterator.next();String name=b.getInputFileName();...return b;}else{return null;}}despite the ...
255
votes
7answers
139k views

How to implement an STL-style iterator and avoid common pitfalls?

I made a collection for which I want to provide an STL-style, random-access iterator. I was searching around for an example implementation of an iterator but I didn't find any. I know about the need ...
330
votes
6answers
368k views

How can I iterate over files in a given directory?

I need to iterate through all .asm files inside a given directory and do some actions on them. How can this be done in a efficient way?
10
votes
4answers
2k views

Removing from a list while iterating over it

The following code:a=list(range(10))remove=Falsefor b in a:if remove:a.remove(b)remove=not removeprint(a)Outputs [0, 2, 3, 5, 6, 8, 9], instead of [0, 2, 4, 6, 8] when ...
57
votes
5answers
22k views

Iterate over all pairs of consecutive items in a list

Given a listl=[1, 7, 3, 5]I want to iterate over all pairs of consecutive list items (1,7), (7,3), (3,5), i.e.for i in xrange(len(l) - 1):x=l[i]y=l[i + 1]# do somethingI ...
91
votes
9answers
36k views

Iterate an iterator by chunks (of n) in Python? [duplicate]

Can you think of a nice way (maybe with itertools) to split an iterator into chunks of given size?Therefore l=[1,2,3,4,5,6,7] with chunks(l,3) becomes an iterator [1,2,3], [4,5,6], [7]I can think ...
70
votes
18answers
121k views

Adding elements to a collection during iteration

Is it possible to add elements to a collection while iterating over it?More specifically, I would like to iterate over a collection, and if an element satisfies a certain condition I want to add ...
189
votes
7answers
18k views

Why are Standard iterator ranges [begin, end) instead of [begin, end]?

Why does the Standard define end() as one past the end, instead of at the actual end?
78
votes
4answers
32k views

How does RecursiveIteratorIterator work in PHP?

How does RecursiveIteratorIterator work? The PHP manual has nothing much documented or explained. What is the difference between IteratorIterator and RecursiveIteratorIterator?
39
votes
4answers
5k views

Flattening iterator

Is there any existing iterator implementation (perhaps in boost) which implement some sort of flattening iterator?For example:unordered_set<vector<int> > s;s.insert(vector<int>(...
376
votes
7answers
235k views

What is the most effective way to get the index of an iterator of an std::vector?

I'm iterating over a vector and need the index the iterator is currently pointing at. AFAIK this can be done in two ways:it - vec.begin()std::distance(vec.begin(), it)What are the pros and cons ...
80
votes
9answers
47k views

What's the best way to iterate over two or more containers simultaneously

C++11 provides multiple ways to iterate over containers. For example:Range-based loopfor(auto c : container) fun(c)std::for_eachfor_each(container.begin(),container.end(),fun)However what is ...
162
votes
15answers
44k views

Why is Java's Iterator not an Iterable?

Why does the Iterator interface not extend Iterable?The iterator() method could simply return this.Is it on purpose or just an oversight of Java's designers?It would be convenient to be able to ...
69
votes
8answers
32k views

Find position of element in C++11 range-based for loop?

Assume I have the following code:vector<int> list;for(auto& elem:list) {int i=elem;}Can I find the position of elem in the vector without maintaining a separate iterator?
188
votes
6answers
142k views

How to correctly implement custom iterators and const_iterators?

I have a custom container class for which I'd like to write the iterator and const_iterator classes.I never did this before and I failed to find an appropriate how-to. What are the guidelines ...
21
votes
3answers
9k views

Using the iterator variable of foreach loop in a lambda expression - why fails?

Consider the following code:public class MyClass{public delegate string PrintHelloType(string greeting);public void Execute(){Type[] types=new Type[] { typeof(string), ...
89
votes
15answers
77k views

Getting number of elements in an iterator in Python

Is there an efficient way to know how many elements are in an iterator in Python, in general, without iterating through each and counting?

153050per page
angop.ao, elkhabar.com, noa.al, afghanpaper.com, bbc.com, time.com, cdc.gov, nih.gov, xnxx.com, github.com,