0

How can the for loop in Python iterate through objects that I cannot address using the [n] notation?

Consider this:

myCollection # Some objects with elements (not a simple list)
for elem in myCollection:
    print elem.Title
myCollection[0]

The code above would in my case succeed in the for loop and will print the title string of all the elements, while the call to myCollection[0] would fail with the following exception:

TypeError: 'myCollection' object is unsubscriptable

How does the for statement iterate through the objects?

Is there another way to access the first element of the collection when the subscript notation fails?

Background

This comes up in IronPython scripting in the Spotfire application which is why I cannot give a MWE.

Here is a dir(myCollection):

['Equals', 'GetHashCode', 'GetType', 'Item', 'MemberwiseClone', 'Overloads',   'ReferenceEquals', 'ToString', '__call__', '__class__', '__cmp__', '__delattr__', '__delete__', '__doc__', '__get__', '__getattribute__', '__getitem__', '__hash__', '__init__', '__module__', '__name__', '__new__', '__reduce__', '__reduce_ex__', '__repr__', '__self__', '__setattr__', '__str__']

to illustrate the methods defined on this object. It does not have a next or next method and for loops still work here.

3
  • Is there another way to access the first element of the collection when the subscript notation fails? - Try next(iter(myCollection)) Commented Jan 15, 2016 at 12:00
  • This does not work as it complains that "next is not defined" Commented Jan 15, 2016 at 12:31
  • However it works to write: iterator = iter(myCollection) followed by iterator.next() Commented Jan 15, 2016 at 12:32

1 Answer 1

0

The forloop works by calling the private__next__() method, which returns a value.

Sign up to request clarification or add additional context in comments.

3 Comments

That does not seems to be correct (at least not in my example of using IronPython). There is no method next of myCollection. I have edited my question to reflect this
That is why you are getting this error.
No, since the for loop works and there is no next method the for loop cannot be using the next method. The errors only occur for myCollection[0] type access.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.