Sign Up

Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.

Have an account? Sign In

Have an account? Sign In Now

Sign In

Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.

Sign Up Here

Forgot Password?

Don't have account, Sign Up Here

Forgot Password

Lost your password? Please enter your email address. You will receive a link and will create a new password via email.

Have an account? Sign In Now

You must login to ask a question.

Forgot Password?

Need An Account, Sign Up Here

Please briefly explain why you feel this question should be reported.

Please briefly explain why you feel this answer should be reported.

Please briefly explain why you feel this user should be reported.

Sign InSign Up

The Archive Base

The Archive Base Logo The Archive Base Logo

The Archive Base Navigation

  • SEARCH
  • Home
  • About Us
  • Blog
  • Contact Us
Search
Ask A Question

Mobile menu

Close
Ask a Question
  • Home
  • Add group
  • Groups page
  • Feed
  • User Profile
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Buy Points
  • Users
  • Help
  • Buy Theme
  • SEARCH
Home/ Questions/Q 8133745
In Process

The Archive Base Latest Questions

Editorial Team
  • 0
Editorial Team
Asked: June 6, 20262026-06-06T09:43:30+00:00 2026-06-06T09:43:30+00:00

somebody mentioned that the function (in this case a method) below is no good

  • 0

somebody mentioned that the function (in this case a method) below is no good as it modifies a list while iterating over it. Why is this, as it works exactly as I intended. I was actually quite pleased with it… Is there a better way of writing it.

Data structures, function and output as follows:

nodes = { ('foo','bar',1),
          ('foo','baz',1),
          ('baz','gad',0),
          ('boo','moo',1),
          ('goo','loo',0),
          ('bar','far',1),
          ('far','aaa',0) }

class Graph(dict):

    def __missing__(self, key):
        self[key] = set()
        return self[key]

    def add_node_pairs(self, node_pairs):
        for pair in node_pairs:
            nodeA, nodeB, weight = pair
            self[nodeA].add((weight, nodeB))
            self[nodeB].add((weight, nodeA)) 

    def find_paths(self, keys):      
        paths = [(key,) for key in keys if key in self]
        for path in paths:
            *oldkeys, key = path
            for weight, next_key in self[key]:
                if next_key not in oldkeys:
                    paths.append( path + (weight,next_key) )

        paths.sort()
        return paths

graph = Graph()
graph.add_node_pairs(nodes)
print(graph)
print( graph.find_paths(['foo']))

graph:

{ 'goo': {(0, 'loo')}, 
  'foo': {(1, 'bar'), (1, 'baz')}, 
  'aaa': {(0, 'far')}, 
  'far': {(1, 'bar'), (0, 'aaa')}, 
  'baz': {(0, 'gad'), (1, 'foo')}, 
  'loo': {(0, 'goo')}, 
  'moo': {(1, 'boo')}, 
  'boo': {(1, 'moo')}, 
  'bar': {(1, 'far'), (1, 'foo')}, 
  'gad': {(0, 'baz')} }

find_paths (‘foo’):

[ ('foo',), 
  ('foo', 1, 'bar'), 
  ('foo', 1, 'bar', 1, 'far'), 
  ('foo', 1, 'bar', 1, 'far', 0, 'aaa'), 
  ('foo', 1, 'baz'), 
  ('foo', 1, 'baz', 0, 'gad') ]
  • 1 1 Answer
  • 0 Views
  • 0 Followers
  • 0
Share
  • Facebook
  • Report

Leave an answer
Cancel reply

You must login to add an answer.

Forgot Password?

Need An Account, Sign Up Here

1 Answer

  • Voted
  • Oldest
  • Recent
  • Random
  1. Editorial Team
    Editorial Team
    2026-06-06T09:43:35+00:00Added an answer on June 6, 2026 at 9:43 am

    Consider the three following examples:

    l = [1]
    for x in l:
        if x < 10 # avoid infinite loop
             l.append(x+1)
        print x
    

    This code is correct and is similar to the one you are using. The output is as expected 1..10.
    Appending an item on a for loop is ok (or inserting an item after the current iterator position).

    Now try the same example but with an insert instead:

    l = [1]
    for x in l:
        if x < 10 # avoid infinite loop
             l.insert(0,x+1)
        print x
    

    This time, you’ll end up with a infinite loop. The reason is that the for loop will always check the next item and since we are inserting x at the beginning, the checked item will always be equal to 1. Inserting an item prior to the current iterator position is usually bad.

    Finally check this example:

    l = [1,2,3,4,5]
    for x in l:
         print x
         l.remove(x)
    

    The output of this function will be 1,3,5 different from the expected output: 1,2,3,4,5.
    Therefor, removing items before the current iterator is also bad.

    To simplify things, let’s just say that changing the content of a list while looping should be avoided, unless you know exactly what you are doing and what effects it could cause on the output.

    • 0
    • Reply
    • Share
      Share
      • Share on Facebook
      • Share on Twitter
      • Share on LinkedIn
      • Share on WhatsApp
      • Report

Sidebar

Related Questions

This benchmark appears to show that calling a virtual method directly on object reference
Somebody knows an example of this? an application made with JSF 2.0 and EJB
Somebody said that when your PHP code and application use global variables then it
somebody know what is encoding type of message that client sends to websocket server?
Somebody ask me this question today . What is the need of reference in
Can somebody help me with this. There is HTML code: <h3> <label> <input type=checkbox
Can somebody explain to me why the following works: template<class T> class MyTemplateClass {
Where to find the full list of all tags that are introduced in JSF
This is my piece of code that i gathered from here . private unsafe
Did somebody ever override successfully the method setDragState in MKAnnotationView ? If I try

Explore

  • Home
  • Add group
  • Groups page
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Users
  • Help
  • SEARCH

Footer

© 2021 The Archive Base. All Rights Reserved
With Love by The Archive Base

Insert/edit link

Enter the destination URL

Or link to existing content

    No search term specified. Showing recent items. Search or use up and down arrow keys to select an item.