What does for x, u in enumerate(...) mean?
Yep... the enumerate
built-in function will create a list something like:
[(0, user1),
(1, user2),
(2, user3)]
Note that I don't know any info about your self.__users
that's why I putting that way....
So this line for x, u in enumerate(self.__users):
will return for x
the index and for the u
your user.
Hope that helped
What does object is enumerated mean in C#?
General explainations for enumeration
IEnumerable
is an interface, that is usually implemented by collection types in C#. For example List
, Queue
or Array
.
IEnumerable
provides a method GetEnumerator
which returns an object of type IEnumerator
.
The IEnumerator
basically represents a "forward moving pointer" to elements in a collection.IEnumerator
has:
- the property
Current
, which returns the object it currently points to (e.g. first object in your collection). - a method
MoveNext
, which moves the pointer to the next element. After calling it,Current
will hold a reference to the second object in your collection.MoveNext
will returnfalse
if there were no more elements in the collection.
Whenever a foreach
loop is executed, the IEnumerator
is retreived and MoveNext
is called for each iteration - until it eventually returns false
. The variable you define in your loop header, is filled with the IEnumerator
's Current
.
Compiling a foreach loop
thx to @Llama
This code...
List<int> a = new List<int>();
foreach (var val in a)
{
var b = 1 + val;
}
is transformed to something like this by the compiler:
List<int> list = new List<int>();
List<int>.Enumerator enumerator = list.GetEnumerator();
try
{
while (enumerator.MoveNext())
{
int current = enumerator.Current;
int num = 1 + current;
}
} finally {
((IDisposable)enumerator).Dispose();
}
The quote
The query represented by this method is not executed until the object
is enumerated either by calling its GetEnumerator method directly or
by using foreach in Visual C#.
GetEnumerator
is automatically called, as soon as you put your object into a foreach
loop, for example. Of course, other functions, e.g. Linq queries, can also retreive the IEnumerator
from your collection, by doing so either explicit (call GetEnumerator
) or implicit in some sort of loop, like I did in my sample above.
What Does Enumerate Do in This Context [Python]
enumerate
is used to generate a line index, the i
variable, together with the line
string, which is the i-th line in the text file. Getting an index from an iterable is such a common idiom on any iterable
that enumerate
provides an elegant way to do this. You could, of course, just initialize an integer counter i
and increment it after each line is read, but enumerate does that for you. The main advantage is code readability: the i
variable initialization and increment statements would be book-keeping code that is not strictly necessary to show the intent of what that loop is trying to do. Python excels at revealing the business-logic of code being concise and to the point.
You can look at Raymond Hettinger's presentation to learn more about idiomatic python from these excellent notes.
Working of Enumerate in Python
enumerate
creates a generator function that effectively turns a list of values into a list of tuples.
L1 = [9, 12, 9, 6]
becomes
[(0, 9), (1, 12), (2, 9), (3, 6)]
The max
function finds the maximum value in that list. If no other arguments were provided to max
, it would compare the tuples
to each other and this item would be the max - (3, 6)
. But that's not what we want. We don't want it to use the enumerate
number in the comparison.
max
accepts a key
argument, which should be a function that takes one argument, which will be the value from the list, and should return a value that will be used to sort the list and choose a maximum. In this case, we want to sort the list based on the second number in each tuple (i.e the 6
in (3, 6)
).
operator.itemgetter
is a function that returns a function, which will return an indexed item of the thing it's called on. For example:
L1 = [3, 4, 6, 2]
f = operator.itemgetter(0)
f(L1)
# 3
f = operator.itemgetter(2)
f(L1)
# 6
In this case, it uses operator.itemgetter(1)
, which is going to return the 6
in (3, 6)
So the result we get from max(enumerate(l1), key=operator.itemgetter(1))
is a tuple
with the index of the max value and the max value in L1
.
Difference between Iterator and Enumerator object
Your understanding of what it ultimately does is correct, but the phrasing in that quote is misleading. There is no difference between an "enumerator" (not really a standard term) and an iterator, or rather, the "enumerator" is a kind of iterator. enumerate
returns an enumerate
object, so enumerate
is a class:
>>> enumerate
<class 'enumerate'>
>>> type(enumerate)
<class 'type'>
>>> enumerate(())
<enumerate object at 0x10ad9c300>
Just like other built-in types list
:
>>> list
<class 'list'>
>>> type(list)
<class 'type'>
>>> type([1,2,3]) is list
True
Or custom types:
>>> class Foo:
... pass
...
>>> Foo
<class '__main__.Foo'>
<class 'type'>
>>> type(Foo())
<class '__main__.Foo'>
>>>
enumerate
objects are iterators. It is not that they can be "treated like" iterators, they are iterators, Iterators are any types that fulfill the following criteria: they define a __iter__
and __next__
:
>>> en = enumerate([1])
>>> en.__iter__
<method-wrapper '__iter__' of enumerate object at 0x10ad9c440>
>>> en.__next__
<method-wrapper '__next__' of enumerate object at 0x10ad9c440>
And iter(iterator) is iterator
:
>>> iter(en) is en
True
>>> en
<enumerate object at 0x10ad9c440>
>>> iter(en)
<enumerate object at 0x10ad9c440>
See:
>>> next(en)
(0, 1)
Now, to be specific, it doesn't return an index value per se, rather, it returns a two-tuple containing the next value in the iterable passed in along with monotonically increasing integers, by default starting at 0
, but it can take a start
parameter, and the iterable passed in doesn't have to be indexable:
>>> class Iterable:
... def __iter__(self):
... yield 1
... yield 2
... yield 3
...
>>> iterable = Iterable()
>>> iterable[0]
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: 'Iterable' object is not subscriptable
>>> list(enumerate(iterable))
[(0, 1), (1, 2), (2, 3)]
>>> list(enumerate(iterable, start=1))
[(1, 1), (2, 2), (3, 3)]
>>> list(enumerate(iterable, start=17))
[(17, 1), (18, 2), (19, 3)]
Related Topics
What Does the Ellipsis Object Do
How to Connect to a MySQL Database in Python
How to Download Image Using Requests
Changing the "Tick Frequency" on X or Y Axis in Matplotlib
Pass a List to a Function to Act as Multiple Arguments
Understanding the "Is" Operator
Tkinter: How to Use After Method
Recursive Function Returning None in Python
How to Define a Two-Dimensional Array
Saving an Object (Data Persistence)
"Large Data" Workflows Using Pandas
Changing the "Tick Frequency" on X or Y Axis in Matplotlib
How to Measure Elapsed Time in Python