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.

HansHarhoff
  • 1,917
  • 2
  • 22
  • 32

1 Answers1

0

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

Oisin
  • 770
  • 8
  • 22
  • 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 – HansHarhoff Jan 15 '16 at 12:18
  • That is why you are getting this error. – Oisin Apr 06 '16 at 16:11
  • 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. – HansHarhoff Apr 06 '16 at 17:05