Tuesday, 27 August 2013

why the list behaves differently in python and Java?

why the list behaves differently in python and Java?

I am learning the scripting language, python. I know Java quite a bit. I
am trying to translate one bit of code from Java to python. but they
behave erratically (or my understanding could be totally wrong) I have the
following code in Java, where I am adding elements to a ArrayList
indefinitely. so this causes outofmemory error, which I expect:
import java.util.*;
public class Testing{
public static void main(String[] args){
ArrayList<Integer> list = new ArrayList<Integer>();
list.add(5);
list.add(4);
for (int i=0;i<list.size();i++){
list.add(5);
}
}
}
now the same code translated in python:
lst = []
lst.append(5)
lst.append(4)
for i in range(len(lst)):
lst.append(5)
print lst
here I get the output: [5, 4, 5, 5]
from what I see, is the list not passed as reference to the for-loop in
python?
similarly here,
>>> l=[1,2,3]
>>> for i in l[:]:
... l.append(4)
... print l
...
[1, 2, 3, 4]
[1, 2, 3, 4, 4]
[1, 2, 3, 4, 4, 4]
in each iteration inside for-loop, I am increasing the list size, so the
iteration should go forever correct?

No comments:

Post a Comment