Modifying Element In For List

Steven D'Aprano steve-REMOVE-THIS at cybersource.com.au
Tue Nov 16 00:17:37 EST 2010


On Mon, 15 Nov 2010 08:31:52 -0800, octopusgrabbus wrote:

> My question concerns elementary list and pass by reference:

What does pass-by-reference have to do with Python? Python doesn't use 
pass-by-reference... if you think it does, you have misunderstood 
something.

Hint: if you think Python has pass-by-reference, please write a procedure 
that takes two generic arguments, and swaps their values, like so:

a = 1
b = 2
swap(a, b)
assert a == 2
assert b == 1

This is the canonical test for pass by reference semantics.


> I've written a function which is passed a list that contains rows read
> from a csv file. 


What are the rows? Lists? Tuples? Something else?


> The function traverses csv_rows, row by row, and
> inspects the first element in each row. The function tests for '', and
> if true, replaces that with a 0.
> 
> I've used the standard Python for syntax for this.

As opposed to C++ syntax or Lisp syntax?

You can't write Python code without using Python syntax, so I'm not sure 
what you mean here.


> def cleanMeterID(csv_rows, bad_meter_id_count):
>     d = drIdx()
> 
>     row_number = 0
> 
>     for row in csv_rows:
>         if False == is_number(row[d.MeterID]):
>             csv_rows[row_number][d.MeterID] = 0
>             row_number = row_number + 1
>             bad_meter_id_count[0]= bad_meter_id_count[0] + 1
> 
>     print("Received ", bad_meter_id_count[0], " bad meter ids")
> 
> I believe the logic show above is flawed, because I am not modifying
> elements in the original csv_rows list.


Are you sure about that? What happens when you try it?



> I would modify this to use an
> index to traverse the list like

This is nearly always the wrong solution in Python.




-- 
Steven



More information about the Python-list mailing list