rabid logic

    • 0
      23 Aug 2012

      To Remove Extra Spaces From A String in Python

      • Edit
      • Delete
      • Tags
      • Autopost

      >>> a='To be    or      not to   be'
      >>> ' '.join(a.split())
      'To be or not to be'

       

      Use ' '.join(a.split())

      • views
      • Tweet
    • 0
      5 Sep 2011

      Removing list elements by looping

      • Edit
      • Delete
      • Tags
      • Autopost
      While looping through a list - list index nos. 0- n are used to iterate through the list items

      parent = ['a', 'b', 'c', 'd', 'e', 'f', 'g']
      child = ['a', 'b', 'c', 'd']

      child index nos.
      a = 0
      b = 1
      c=  2
      d = 3

      If there is a need to remove items from one list based on those present in another (parent) - logically it would require iterating through the child list and removing those items that exist in the parent list

      so the foll code should do the trick..

      parent = ['a', 'b', 'c', 'd', 'e', 'f', 'g']
      child = ['a', 'b', 'c', 'd']

      for c in child:
       if c in parent:
        child.remove(c)

      however if you print child it will output [b,d]

      The reason is that python resets the index nos. of the list after the removal of an item. 
      So in effect after 'a' (index 0) is removed from the child list - 'b' is set as index 0. The next loop by will pass index 1 which is now 'c'. As a consequence 'b' never enters the loop and therefore not checked if it exists in the parent list and hence not removed.

      Solution:
      Instead of using the actual list in the for loop, iterate through a copy of the list using [:] and carry out the removal from the original list.

      parent = ['a', 'b', 'c', 'd', 'e', 'f', 'g']
      child = ['a', 'b', 'c', 'd']

      for c in child[:]:
       if c in parent:
        child.remove(c)

      now when you print child the output is as expected an empty list []
      • views
      • Tweet
    • Search

    • Tags

      • Ubuntu
      • Virtualbox
      • work around
      • authetication
      • remove spaces
      • convert to words
      • currency
      • format
      • format string
      • indian
      • jasper
      • jasper server
      • lists
      • openerp
      • remove()
    • Obox Design
  • rabid logic


    364 Views
  • Get Updates

    Subscribe via RSS