473,785 Members | 2,234 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

list.remove() inside for item in aList:

bartonc
6,596 Recognized Expert Expert
I was chasing a bug last night. I actually saw it before I inserted the trace (print) statements. This:
Expand|Select|Wrap|Line Numbers
  1. >>> l=range(10)
  2. >>> for i in l:
  3. ...     l.remove(i)
  4. ...     print i
  5. ...     
0
2
4
6
8
shows interesting side effects of removing items while looping on a list's items.

However, it works working backwards in the list:
Expand|Select|Wrap|Line Numbers
  1. >>> l=range(10)
  2. >>> for i in l[::-1]:
  3. ...     l.remove(i)
  4. ...     print i
  5. ...     
9
8
7
6
5
4
3
2
1
0
Jun 28 '07 #1
4 1867
ghostdog74
511 Recognized Expert Contributor
Expand|Select|Wrap|Line Numbers
  1. >>> l=range(10)
  2. >>> for i in l[:]:
  3. ...  l.remove(i)
  4. ...  print i
  5. ...
  6.  
  7. 1
  8. 2
  9. 3
  10. 4
  11. 5
  12. 6
  13. 7
  14. 8
  15. 9
  16. >>>
  17.  
  18.  
Jun 28 '07 #2
r035198x
13,262 MVP
I was chasing a bug last night. I actually saw it before I inserted the trace (print) statements. This:
Expand|Select|Wrap|Line Numbers
  1. >>> l=range(10)
  2. >>> for i in l:
  3. ...     l.remove(i)
  4. ...     print i
  5. ...     
0
2
4
6
8
shows interesting side effects of removing items while looping on a list's items.

However, it works working backwards in the list:
Expand|Select|Wrap|Line Numbers
  1. >>> l=range(10)
  2. >>> for i in l[::-1]:
  3. ...     l.remove(i)
  4. ...     print i
  5. ...     
9
8
7
6
5
4
3
2
1
0
My explanation is that in l[::-1]: a temporary shallow copy of the list is created and this is where the values of i are read from, but for
Expand|Select|Wrap|Line Numbers
  1. >>> for i in l:
The values of i are skiping one each time because after every removal, the elements' positions shift left by one.
Jun 28 '07 #3
bartonc
6,596 Recognized Expert Expert
My explanation is that in l[::-1]: a temporary shallow copy of the list is created and this is where the values of i are read from, but for
Expand|Select|Wrap|Line Numbers
  1. >>> for i in l:
The values of i are skiping one each time because after every removal, the elements' positions shift left by one.
Exactly right! That's why ghostdog74's code works going forward. It was 4:20 AM PST when I posted that. By 9:45 that thought had occurred to me, but I was away from the computer.
Jun 28 '07 #4
r035198x
13,262 MVP
Exactly right! That's why ghostdog74's code works going forward. It was 4:20 AM PST when I posted that. By 9:45 that thought had occurred to me, but I was away from the computer.
And i'm still a Python newbie.
Wait till I can give it more time.
Jun 29 '07 #5

Sign in to post your reply or Sign up for a free account.

Similar topics

4
2963
by: Bart Nessux | last post by:
New to Python... trying to figure out how to count the objects in a list and then map the count to the objects or convert the list to a dict... I think the latter would be better as I need a number associated with each entry. Any pointers? Also, does this bit of code look to be truely random? def random_number_gen(): winner = winner.append(random.sample(xrange(100000), 1))
3
1169
by: GrelEns | last post by:
hello, having a list like i would like to get , , , , , ]
6
2898
by: aurora | last post by:
I find that I use some list unpacking construct very often: name, value = s.split('=',1) So that 'a=1' unpack as name='a' and value='1' and 'a=b=c' unpack as name='a' and value='b=c'. The only issue is when s does not contain the character '=', let's say it is 'xyz', the result list has a len of 1 and the unpacking would fail. Is there some really handy trick to pack the result list into len of 2 so
5
1426
by: Nick L | last post by:
I've hit a brick wall on something that I'm guessing is pretty simple but it's driving me nuts. I noticed that with python lists, generally when you make a copy of a list (ie, List1 = List2) List1 just becomes a reference to List2 and any modifications done to List1 affects List2. Ok I can live with this but I want to make a completely seperate copy not attached to the original in anyway. So then I used this method. List1 = List2 . This...
17
5328
by: Rainer Queck | last post by:
Hi NG, one more question about thread safety of generic lists. Let's assume a generic list: List<MyTyp> aList = new List<MyType>(); Would it be a problem if one thread removes elements from the list like MyTyp x = aList; aList.Remove(x);
5
4603
by: Allerdyce.John | last post by:
In STL list, is it safe to do this: list<A> aList; //private attribute of MyClass void MyClass:: aMethod() { list<A>::Iterator iter; for ( iter = aList.begin() ; iter != aList.end() ; iter++) { A a = (*iter);
5
1813
by: micklee74 | last post by:
hi i have a list with contents like this alist = how can i "convert" this list into a dictionary such that dictionary = { '>QWER':'askfhs' , '>REWR' : 'sfsdf' , '>FGDG', 'sdfsdgffdgfdg' }
3
1174
by: Gregory Piñero | last post by:
I'm going to assume that it's supposed to work like this, but could someone tell me the reasoning behind it? I.E. why is 3 skipped? .... print item .... if item==2: .... alist.remove(item) .... 1 2
6
7479
by: Steven D'Aprano | last post by:
If I want to iterate over part of the list, the normal Python idiom is to do something like this: alist = range(50) # first item is special x = alist # iterate over the rest of the list for item in alist x = item
0
9645
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
9481
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
10341
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...
0
10155
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 tapestry of website design and digital marketing. It's not merely about having a website; it's about crafting an immersive digital experience that captivates audiences and drives business growth. The Art of Business Website Design Your website is...
0
9954
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 protocol has its own unique characteristics and advantages, but as a user who is planning to build a smart home system, I am a bit confused by the choice of these technologies. I'm particularly interested in Zigbee because I've heard it does some...
1
7502
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
5513
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
1
4054
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
3
2881
bsmnconsultancy
by: bsmnconsultancy | last post by:
In today's digital era, a well-designed website is crucial for businesses looking to succeed. Whether you're a small business owner or a large corporation in Toronto, having a strong online presence can significantly impact your brand's success. BSMN Consultancy, a leader in Website Development in Toronto offers valuable insights into creating effective websites that not only look great but also perform exceptionally well. In this comprehensive...

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.