473,804 Members | 2,007 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

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 1946
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__(sel f, 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(myLis t)):
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__(sel f, 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(myLis t)):
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
3760
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 ------------------------------------------------------------- PEP: 323
59
4357
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 HTML version is much more readable than the ReST version. See: http://www.python.org/peps/pep-0322.html
10
2763
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! print "next"
2
2084
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 useListIteration(): list = result = "" for item in list: result += item return result
1
425
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. { .... system("cls"); printf("\nIteration:%d", i);
75
5647
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 complexity as I go. Here's a simple one I tried out: #include<stdio.h> /* To compare the the time and space cost of iteration against
0
1630
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
4053
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? Bill
4
3659
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 subset of myList ... } vs
1
3369
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 the iteration variable is used and you cannot modify it. For example: int pins = {9, 3, 7, 2} int newPin = 10; foreach(int pin in pins) {
0
9716
marktang
by: marktang | last post by:
ONU (Optical Network Unit) is one of the key components for providing high-speed Internet services. Its primary function is to act as an endpoint device located at the user's premises. However, people are often confused as to whether an ONU can Work As a Router. In this blog post, we’ll explore What is ONU, What Is Router, ONU & Router’s main usage, and What is the difference between ONU and Router. Let’s take a closer look ! Part I. Meaning of...
0
9596
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 effortlessly switch the default language on Windows 10 without reinstalling. I'll walk you through it. First, let's disable language synchronization. With a Microsoft account, language settings sync across devices. To prevent any complications,...
0
10604
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, it seems that the internal comparison operator "<=>" tries to promote arguments from unsigned to signed. This is as boiled down as I can make it. Here is my compilation command: g++-12 -std=c++20 -Wnarrowing bit_field.cpp Here is the code in...
1
10361
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 Update option using the Control Panel or Settings app; it automatically checks for updates and installs any it finds, whether you like it or not. For most users, this new feature is actually very convenient. If you want to control the update process,...
0
9179
agi2029
by: agi2029 | last post by:
Let's talk about the concept of autonomous AI software engineers and no-code agents. These AIs are designed to manage the entire lifecycle of a software development project—planning, coding, testing, and deployment—without human intervention. Imagine an AI that can take a project description, break it down, write the code, debug it, and then launch it, all on its own.... Now, this would greatly impact the work of software developers. The idea...
1
7644
isladogs
by: isladogs | last post by:
The next Access Europe User Group meeting will be on Wednesday 1 May 2024 starting at 18:00 UK time (6PM UTC+1) and finishing by 19:30 (7.30PM). In this session, we are pleased to welcome a new presenter, Adolph Dupré who will be discussing some powerful techniques for using class modules. He will explain when you may want to use classes instead of User Defined Types (UDT). For example, to manage the data in unbound forms. Adolph will...
0
6874
by: conductexam | last post by:
I have .net C# application in which I am extracting data from word file and save it in database particularly. To store word all data as it is I am converting the whole word file firstly in HTML and then checking html paragraph one by one. At the time of converting from word file to html my equations which are in the word document file was convert into image. Globals.ThisAddIn.Application.ActiveDocument.Select();...
0
5536
by: TSSRALBI | last post by:
Hello I'm a network technician in training and I need your help. I am currently learning how to create and manage the different types of VPNs and I have a question about LAN-to-LAN VPNs. The last exercise I practiced was to create a LAN-to-LAN VPN between two Pfsense firewalls, by using IPSEC protocols. I succeeded, with both firewalls in the same network. But I'm wondering if it's possible to do the same thing, with 2 Pfsense firewalls...
1
4316
by: 6302768590 | last post by:
Hai team i want code for transfer the data from one system to another through IP address by using C# our system has to for every 5mins then we have to update the data what the data is updated we have to send another system

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.