473,320 Members | 1,976 Online
Bytes | Software Development & Data Engineering Community
Post Job

Home Posts Topics Members FAQ

Join Bytes to post your question to a community of 473,320 software developers and data experts.

Understanding While Loop Execution

Hi folks,

I'm still fairly new to programming in python and programming in
general. A friend of mine is in a CompSci 101 course and was working
on a slider game when he encountered a problem. We eventually figured
out what the problem was and built a test case to help solve it, but I
can't for the life of me figure out the why behind it. I tried
googling it and searching the list but didn't find anything that
really explained it. I'm sure it's probably just both of us
misunderstanding what the "while" statement does. So I hoped to ask
for some clarification here. So here is what we worked out was going
on with his code.

from random import shuffle

mylist=[2,1,3]
baselist=[1,2,3]
newlist=[]
count=0
while mylist!=baselist:
count+=1
shuffle(mylist)
newlist.append(mylist)
print count, mylist, newlist

Output:
>>>
1 [3, 1, 2] [[3, 1, 2]]
2 [1, 2, 3] [[1, 2, 3], [1, 2, 3]]
>>>
What he wanted was a list of lists to use later as a replay. What we
expected newlist.append(mylist) to do was to save a copy of mylist
into the collection for each iteration of the while statement.
However, what struck us as odd is that for each time the while loop
executes it changes all the lists in the list. What I found even
exasperating was if I created yet another list.

from random import shuffle

mylist=[2,1,3]
baselist=[1,2,3]
newlist=[]
saved_shufs=[]
count=0

while mylist!=baselist:
count+=1
shuffle(mylist)
newlist.append(mylist)
saved_shufs.append(newlist[0])
print count, mylist, newlist[0], saved_shufs

Output:
>>>
1 [1, 3, 2] [1, 3, 2] [[1, 3, 2]]
2 [3, 2, 1] [3, 2, 1] [[3, 2, 1], [3, 2, 1]]
3 [1, 2, 3] [1, 2, 3] [[1, 2, 3], [1, 2, 3], [1, 2, 3]]
>>>
newlist[0] printed out correctly but when appending it into
saved_shufs it still overwrote everything.

Eventually, after plinking about I remembered that tuples were
immutable and wound up creating a variable like
tuple_of_mylist=tuple(mylist) then appending that into newlist. That
kept the list of tuples fine. I'm still wondering though what I'm not
grasping about "while" that made it do that to the lists? Or is it not
even while, is it something else I'm not getting?

Thanks in advance,
B
Feb 18 '08 #1
3 1595
Brad wrote:
Hi folks,

I'm still fairly new to programming in python and programming in
general. A friend of mine is in a CompSci 101 course and was working
on a slider game when he encountered a problem. We eventually figured
out what the problem was and built a test case to help solve it, but I
can't for the life of me figure out the why behind it. I tried
googling it and searching the list but didn't find anything that
really explained it. I'm sure it's probably just both of us
misunderstanding what the "while" statement does. So I hoped to ask
for some clarification here. So here is what we worked out was going
on with his code.

from random import shuffle

mylist=[2,1,3]
baselist=[1,2,3]
newlist=[]
count=0
while mylist!=baselist:
count+=1
shuffle(mylist)
newlist.append(mylist)
print count, mylist, newlist

Output:

1 [3, 1, 2] [[3, 1, 2]]
2 [1, 2, 3] [[1, 2, 3], [1, 2, 3]]
What he wanted was a list of lists to use later as a replay. What we
expected newlist.append(mylist) to do was to save a copy of mylist
into the collection for each iteration of the while statement.
However, what struck us as odd is that for each time the while loop
executes it changes all the lists in the list. What I found even
exasperating was if I created yet another list.

from random import shuffle

mylist=[2,1,3]
baselist=[1,2,3]
newlist=[]
saved_shufs=[]
count=0

while mylist!=baselist:
count+=1
shuffle(mylist)
newlist.append(mylist)
saved_shufs.append(newlist[0])
print count, mylist, newlist[0], saved_shufs

Output:

1 [1, 3, 2] [1, 3, 2] [[1, 3, 2]]
2 [3, 2, 1] [3, 2, 1] [[3, 2, 1], [3, 2, 1]]
3 [1, 2, 3] [1, 2, 3] [[1, 2, 3], [1, 2, 3], [1, 2, 3]]
newlist[0] printed out correctly but when appending it into
saved_shufs it still overwrote everything.

Eventually, after plinking about I remembered that tuples were
immutable and wound up creating a variable like
tuple_of_mylist=tuple(mylist) then appending that into newlist. That
kept the list of tuples fine. I'm still wondering though what I'm not
grasping about "while" that made it do that to the lists? Or is it not
even while, is it something else I'm not getting?

Thanks in advance,
B
First of all, it's got nothing to do with the while loop. The Python
feature that's biting you here is the fact that lists are not *copied*
when you work with them.

So in the following code, the list named full does not have 3 copies of
sub in it, but rather it has 3 *references* to the single list named
sub. Any changes to the list named sub will be reflected anywhere that
list is referred to.

>>sub = [1,2,3]
full = [sub,sub,sub]
full
[[1, 2, 3], [1, 2, 3], [1, 2, 3]]
>>sub[0] = 123
full
[[123, 2, 3], [123, 2, 3], [123, 2, 3]]
So in you code, the single list mylist is shuffled each time, and
newlist keeps growing my more references to it. If you want a *copy* of
the list, you have to explicitly ask for one. The easiest way to do
that is mylist[:]. (This is a shorthand for copying out any sublist of
mylist via the syntax mylist[a:b], with a and b defaulting to whole list.)

Gary Herron

Feb 18 '08 #2
On Feb 18, 4:53*pm, Gary Herron <gher...@islandtraining.comwrote:
Brad wrote:
Hi folks,
I'm still fairly new to programming in python and programming in
general.
a = [1, 2, 3]
b = a
print a
print b
print

a[0] = 100
print a
print b

--output:--
[1, 2, 3]
[1, 2, 3]

[100, 2, 3]
[100, 2, 3]
Feb 19 '08 #3
Gary Herron <gh*****@islandtraining.comwrote:
>
So in the following code, the list named full does not have 3 copies of
sub in it, but rather it has 3 *references* to the single list named
sub.
Since we are being picky here, it's more accurate to say that the list
"full" contains 3 references to the list that is also referenced by the
name "sub". I've found that it is more useful to think of Python objects
(like lists) as anonymous things living out in object memory (which is, no
doubt, a happy place), and all of the names in the program just refer to
those anonymous things.
>Any changes to the list named sub will be reflected anywhere that
list is referred to.
And vice versa. "sub" is a reference to the list, exactly like "full[0]".
No difference.
>sub = [1,2,3]
full = [sub,sub,sub]
full
[[1, 2, 3], [1, 2, 3], [1, 2, 3]]
>sub[0] = 123
full
[[123, 2, 3], [123, 2, 3], [123, 2, 3]]
And:
>>full[0][2] = 99
sub
[123, 2, 99]
>>full
[[123, 2, 99], [123, 2, 99], [123, 2, 99]]
--
Tim Roberts, ti**@probo.com
Providenza & Boekelheide, Inc.
Feb 19 '08 #4

This thread has been closed and replies have been disabled. Please start a new discussion.

Similar topics

5
by: John Edwards | last post by:
Hello, I have sort of a newbie question. I'm trying to optimize a loop by breaking it into two passes. Example: for(i = 0; i < max; i++) {
24
by: bazad | last post by:
Hi, I'd like to understand consequences of Application.DoEvents call. Does it create a new thread? Thank you
11
by: Roman Töngi | last post by:
for (int i = 1; i <= 10; i++) cout << i << endl; I expected the following: 1 2 3 4 5 6
34
by: sushant | last post by:
hi all, suppose i have 2 loops one inside the other, like this 1) for(i=0;i<=100;i++) { for(j=0;j<=10;j++) { some code; }
22
by: Jan Richter | last post by:
Hi there, the Code below shows DJBs own implementation of strlen (str_len): unsigned int str_len(char *s) { register char *t; t = s; for (;;) { if (!*t) return t - s; ++t;
1
by: rlm | last post by:
When I attempt to manage Transactions in a WHILE LOOP @@TRANCOUNT is off. I obviously do not understand error handling as I should. In the loop below where does the point of execution move to after...
7
by: Buck Rogers | last post by:
Hi all! Newbie here. Below is an example from Teach Yourself C in 21 Days. My apologies if it is a bit long. What I don't understand is how the "get_data" function can call the...
4
by: joelagnel | last post by:
I'm new to .NET and have a basic understanding of operating systems. I can also do some magic in Csharp, but I lack an understanding of what's going on under the hood, with respect to how windows...
16
by: Andy B | last post by:
I have the following code inside of a WebBrowser.DocumentCompleted event: For index As Integer = 0 To Me.Browser.Document.GetElementsByTagName("ul").Item(0).GetElementsByTagName("li").Count ...
0
by: DolphinDB | last post by:
Tired of spending countless mintues downsampling your data? Look no further! In this article, you’ll learn how to efficiently downsample 6.48 billion high-frequency records to 61 million...
0
by: ryjfgjl | last post by:
ExcelToDatabase: batch import excel into database automatically...
0
isladogs
by: isladogs | last post by:
The next Access Europe meeting will be on Wednesday 6 Mar 2024 starting at 18:00 UK time (6PM UTC) and finishing at about 19:15 (7.15PM). In this month's session, we are pleased to welcome back...
0
by: jfyes | last post by:
As a hardware engineer, after seeing that CEIWEI recently released a new tool for Modbus RTU Over TCP/UDP filtering and monitoring, I actively went to its official website to take a look. It turned...
0
by: ArrayDB | last post by:
The error message I've encountered is; ERROR:root:Error generating model response: exception: access violation writing 0x0000000000005140, which seems to be indicative of an access violation...
1
by: PapaRatzi | last post by:
Hello, I am teaching myself MS Access forms design and Visual Basic. I've created a table to capture a list of Top 30 singles and forms to capture new entries. The final step is a form (unbound)...
0
by: CloudSolutions | last post by:
Introduction: For many beginners and individual users, requiring a credit card and email registration may pose a barrier when starting to use cloud servers. However, some cloud server providers now...
1
by: Shællîpôpï 09 | last post by:
If u are using a keypad phone, how do u turn on JavaScript, to access features like WhatsApp, Facebook, Instagram....
0
isladogs
by: isladogs | last post by:
The next Access Europe User Group meeting will be on Wednesday 3 Apr 2024 starting at 18:00 UK time (6PM UTC+1) and finishing by 19:30 (7.30PM). In this session, we are pleased to welcome former...

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.