473,395 Members | 1,761 Online
Bytes | Software Development & Data Engineering Community
Post Job

Home Posts Topics Members FAQ

Join Bytes to post your question to a community of 473,395 software developers and data experts.

for iteration

Hello,

I'm trying to customize a list by overriding __getitem__ method but
this change seems to not work with for iteration.
When I use my customized list in a for iteration, all changes made
in __getitem__ are not take into account.
How can I modify this behaviour ?

Thanks
Jul 18 '05 #1
2 1937
Franck Bui-Huu wrote:
Hello,

I'm trying to customize a list by overriding __getitem__ method but
this change seems to not work with for iteration.
When I use my customized list in a for iteration, all changes made
in __getitem__ are not take into account.
How can I modify this behaviour ?

Thanks


For the for loop to work properly, you have to overide the __iter__()
method, e.g.:

class MyList(list):
def __getitem__(self, index):
""" for the sake of this example convert item to uppercase """
return list.__getitem__(self, index).upper()
def __iter__(self):
""" implemented using a generator """
for i in range(len(self)):
yield self[i] # calls the customized __getitem__()

myList = MyList(["alpha", "beta", "gamma"])

# works with __getitem__()
for index in range(len(myList)):
print myList[index]

print

# works with __iter__()
for item in myList:
print item

Peter
Jul 18 '05 #2
Thanks for your example but I haven't found __iter__ method in list type:
dir(list) ['__add__', '__class__', '__contains__', '__delattr__', '__delitem__',
'__delsli
ce__', '__doc__', '__eq__', '__ge__', '__getattribute__', '__getitem__',
'__gets
lice__', '__gt__', '__hash__', '__iadd__', '__imul__', '__init__',
'__le__', '__
len__', '__lt__', '__mul__', '__ne__', '__new__', '__reduce__',
'__repr__', '__r
mul__', '__setattr__', '__setitem__', '__setslice__', '__str__',
'append', 'coun
t', 'extend', 'index', 'insert', 'pop', 'remove', 'reverse', 'sort']

Do you know why ?

Peter Otten a écrit:
Franck Bui-Huu wrote:
Hello,

I'm trying to customize a list by overriding __getitem__ method but
this change seems to not work with for iteration.
When I use my customized list in a for iteration, all changes made
in __getitem__ are not take into account.
How can I modify this behaviour ?

Thanks


For the for loop to work properly, you have to overide the __iter__()
method, e.g.:

class MyList(list):
def __getitem__(self, index):
""" for the sake of this example convert item to uppercase """
return list.__getitem__(self, index).upper()
def __iter__(self):
""" implemented using a generator """
for i in range(len(self)):
yield self[i] # calls the customized __getitem__()

myList = MyList(["alpha", "beta", "gamma"])

# works with __getitem__()
for index in range(len(myList)):
print myList[index]

print

# works with __iter__()
for item in myList:
print item

Peter

Jul 18 '05 #3

This thread has been closed and replies have been disabled. Please start a new discussion.

Similar topics

35
by: Raymond Hettinger | last post by:
Here is a discussion draft of a potential PEP. The ideas grew out of the discussion on pep-284. Comments are invited. Dart throwing is optional. Raymond Hettinger ...
59
by: Raymond Hettinger | last post by:
Please comment on the new PEP for reverse iteration methods. Basically, the idea looks like this: for i in xrange(10).iter_backwards(): # 9,8,7,6,5,4,3,2,1,0 <do something with i> The...
10
by: Florian Lindner | last post by:
Hi! If I iterate through a list, is there a way I can get the number of the iteration: first, second, third, ... l = for x in l print x print x.iteration() # <- That's what I'm looking for!...
2
by: Abdullah Khaidar | last post by:
Is there any iteration style we must use to get faster processing time? I've tried with some style to concat number in list. But I still don't know which one is the recommended style. >>> def...
1
by: karthigan | last post by:
I am writing a simple hardware test program in C that would run from Windows command line. Inside one of the loops, I have this code fragment that would display the Iteration count. { .......
75
by: Sathyaish | last post by:
Can every problem that has an iterative solution also be expressed in terms of a recursive solution? I tried one example, and am in the process of trying out more examples, increasing their...
0
by: mkyrou | last post by:
Community > Programming Help > .NET crystal report and iteration mkyrou Junior Member 3 Posts Today 01:09 PM #1 crystal report and iteration
9
by: news.microsoft.com | last post by:
I am looping through an iteration and I would like to test the next item but if its not the one that I want how do I put it back so that when my foreach continues it is in the next iteration? ...
4
by: John A Grandy | last post by:
Is there a performance difference between forward iteration and reverse iteration through a List<string? for ( i = 0; i < myList.Count; i++ ) { // do work, such as forward iterate through a...
1
by: greyseal96 | last post by:
Hi, I am a pretty new programmer, so I apologize in andvance if this is a dumb question... In a book that I'm reading to learn C#, it says that when using a foreach() loop, a read-only copy of...
0
by: Charles Arthur | last post by:
How do i turn on java script on a villaon, callus and itel keypad mobile phone
0
by: ryjfgjl | last post by:
In our work, we often receive Excel tables with data in the same format. If we want to analyze these data, it can be difficult to analyze them because the data is spread across multiple Excel files...
0
by: emmanuelkatto | last post by:
Hi All, I am Emmanuel katto from Uganda. I want to ask what challenges you've faced while migrating a website to cloud. Please let me know. Thanks! Emmanuel
1
by: nemocccc | last post by:
hello, everyone, I want to develop a software for my android phone for daily needs, any suggestions?
0
by: Hystou | last post by:
Most computers default to English, but sometimes we require a different language, especially when relocating. Forgot to request a specific language before your computer shipped? No problem! You can...
0
Oralloy
by: Oralloy | last post by:
Hello folks, I am unable to find appropriate documentation on the type promotion of bit-fields when using the generalised comparison operator "<=>". The problem is that using the GNU compilers,...
0
jinu1996
by: jinu1996 | last post by:
In today's digital age, having a compelling online presence is paramount for businesses aiming to thrive in a competitive landscape. At the heart of this digital strategy lies an intricately woven...
0
by: Hystou | last post by:
Overview: Windows 11 and 10 have less user interface control over operating system update behaviour than previous versions of Windows. In Windows 11 and 10, there is no way to turn off the Windows...
0
tracyyun
by: tracyyun | last post by:
Dear forum friends, With the development of smart home technology, a variety of wireless communication protocols have appeared on the market, such as Zigbee, Z-Wave, Wi-Fi, Bluetooth, etc. Each...

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.