Wednesday, May 25, 2011

cshell redirection

Character Action

>
Redirect standard output

>&
Redirect standard output and standard error

<
Redirect standard input

>!
Redirect standard output; overwrite file if it exists

>&!
Redirect standard output and standard error; overwrite file if it exists

|
Redirect standard output to another command (pipe)

>>
Append standard output

>>&
Append standard output and standard error

Tuesday, May 10, 2011

[python] Parameters: pass by value or ref?

C is pass-by-value.
Java is pass-by-value.
Python passes references-to-objects by value (like Java), and everything in Python is an object.

Some objects, like strings, tuples, and numbers, are immutable. Altering them inside a function/method will create a new instance and the original instance outside the function/method is not changed.

Other objects, like lists and dictionaries are mutable, which means you can change the object in-place. Therefore, altering an object inside a function/method will also change the original object outside. Assigning a separate object (e.g. creating a new instance) to the input parameter will also not change the original instance.


   def  no_change0(val)
          val *= 2   #original val is not changed.
         
    def  no_change1(inst)
          inst = {}
          inst['anything'] = 'something'  #original inst is not changed!!!


   def  change1(inst)
          inst['anything'] = 'something'  #original inst is changed this time.

[python] How to iterate through a list

  • basic iteration 
Iterating through a list in Python is simple using a for in loop.
colours = ["red","green","blue"]

for colour in colours:
    print colour
  • enumerate 
To iterate through the same list using an index we can apply the enumerate() function.
colours = ["red","green","blue"]

for i, colour in enumerate(colours):
    print i, colour

  • Remove elements as you traverse a list
iterate over a copy of the list:
for c in colors[:]:
    if c == 'green':
        colors.remove(c)
Hereby colors[:] is a copy (a weird but, sigh, idiomatic way to spell list(colors)) so it doesn't get affected by the .remove calls