Python Forum
Old brain - New Language - Question on loops
Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
Old brain - New Language - Question on loops
#1
Hi folks,

I am an older fella, who has worked in and around IT for many years and who decided to take on a new challenge and learn to code - I haven't done any coding since about 1987 when I did a small amount of C and PASCAL in college when I left the military. My Cyber Security colleagues convinced me that Python was the way to go so i've got an online tutorial underway along with an eBook from NoStarchPress.

Because my brain doesn't retain things as it did in 1987 I need to do and redo some stuff to get it to sink in so I try to adapt some of the exercises and lessons after we complete a section to confirm my understanding. When we were playing with lists and loops I tried to combine the two subjects and I have some unexpected behaviour. I am hoping that I can develop my skills with the help of the forum and later give back to any other newcomers, but for now I am afraid this is brand new to me - Ive been at it for two weekends.

I am using a Mac on High Sierra, Sublime Text as an editor, pre-instaalled Python (2.7.10)

this is my simple code to practice with lists and loops, I create a list, add to the list, remove items from the list and move them to a second list:

 # -*- coding: utf-8 -*-
# start with a newlist
guests = ['David', 'Adolf','Charles']
print(guests)

# add some more entries to the list, add to first, second and last
guests.insert(0, 'Geoff')
guests.insert(1, 'Colin')
guests.append('Fred')

print(guests) # print the list to check its valid
print('\n')

# start to remove guests and add them to an alternate list
removedlist = []

print('there are ' + str(len(guests)) + ' items in the list \n')
for guest in guests:
	popped=guests.pop()
	removedlist.append(popped)
	print('last popped value - ' + popped)
	print('current guests list')
	print(guests)
	print('the following have been removed')
	print(removedlist)
	print('\n')
I expected the for loop to iterate six times and for all the entries in "guests" to end up in "removedlist" but it only appears to iterate three times:

This is the output:

Output:
['David', 'Adolf', 'Charles'] ['Geoff', 'Colin', 'David', 'Adolf', 'Charles', 'Fred'] there are 6 items in the list last popped value - Fred current guests list ['Geoff', 'Colin', 'David', 'Adolf', 'Charles'] the following have been removed ['Fred'] last popped value - Charles current guests list ['Geoff', 'Colin', 'David', 'Adolf'] the following have been removed ['Fred', 'Charles'] last popped value - Adolf current guests list ['Geoff', 'Colin', 'David'] the following have been removed ['Fred', 'Charles', 'Adolf'] [Finished in 0.1s]
All help and guidance is appreciated on both this query and the wider "how to learn python" question
Reply
#2
Quote:Because my brain doesn't retain things as it did in 1987
You're too young for this! Need to go on Gluten Free Diet. I will vouch for it, 70+ YO.

Quote:and the wider "how to learn python" question
Trying things like you're doing now is good.
I recommend this tutorial (my favorite): https://www.python-course.eu/python3_course.php

i also recommend installing VSCode (Not Visual Studio, unrelated to MS) with it you can run the debugger, and
watch the guests list expand and contract as you execute step by step.
Output:
guests = ['David', 'Adolf','Charles'] Guests: ['David', 'Adolf','Charles'] guests.insert(0, 'Geoff') Guests: ['Geoff', 'David', 'Adolf','Charles'] guests.insert(1, 'Colin') Guests: ['Geoff', 'Colin', 'David', 'Adolf', 'Charles'] guests.append('Fred') Guests: ['Geoff', 'Colin', 'David', 'Adolf', 'Charles', 'Fred'] there are 6 items in the list Iteration 1: for guest in guests: # Here's the problem, see below popped=guests.pop() ['Geoff', 'Colin', 'David', 'Adolf', 'Charles'] last popped value - Fred
The problem is that you are using the contents of the list to control the iterations.
The contents is a moving target so soesn't perform as you expect.
If you want to xcontinue until the list is empty, instead of loop, use:
while guests:
    popped=guests.pop()
    removedlist.append(popped)
    ...
Reply
#3
Hello and welcome to Python and the forums!

The reason your loop stops is that for loop uses the same list for iterating through as the list you pop elements out of. So after 3 iterations, there are no more elements to iterate through, because they were popped out of the list in previous iterations.
To overcome this, you can instead iterate through a copy of the original list, which can be achieved like this:
# my_list[:] will make a copy of my_list 
for guest in guests[:]:
I'm not sure whether it is something you should be too bothered about at this point, but we strongly encourage people to use Python 3 instead of Python 2. If you are dedicated to a long term Python learning, it might be a good idea to make the (rather hassle-free) switch.

Edit:
I like @Larz's solution better =)
Reply
#4
I've returned to programming as well, having used assembly, Fortran, Pascal, Ada, Algol in the past and then into other IT stuff for a few decades.

Something that helped me a lot was the Loop like a native video on YouTube.
I am trying to help you, really, even if it doesn't always seem that way
Reply
#5
https://python-forum.io/Thread-more-loop...0#pid59520
Reply
#6
Thanks for all replies... that makes sense - its not the behaviour I expected but I understand whats happening.

pcsailor - I'll watch the vid when I get five

Larz60+ - I'm closer to you than you'd imagine, thanks for the information.

j.crater - thanks for the information re Python 3 - its installed I wasn't sure which to use I have an old tutorial that is still using V2 so I started there but the book seems to be more aimed at V3 - I'll change the shebang and the builder to use V3

Ian
Reply
#7
The for loop is basically syntactic sugar for a while loop, and this is one of the ways where the underlying method makes itself visible. The for loop keeps track of what position it's currently at in the list, and increases that each time. So if you change the list while looping over it, you get weird results (like you're seeing).

Sort of like this:
>>> guests = ['Geoff', 'Colin', 'David', 'Adolf', 'Charles', 'Fred']
>>> index = 0
>>> while index < len(guests):
...   current = guests[index]
...   index += 1
...   removed = guests.pop()
...   print(f"Iteration: {index}\tRemoved: {removed}\tRemaining: {guests}")
...
Iteration: 1    Removed: Fred   Remaining: ['Geoff', 'Colin', 'David', 'Adolf', 'Charles']
Iteration: 2    Removed: Charles        Remaining: ['Geoff', 'Colin', 'David', 'Adolf']
Iteration: 3    Removed: Adolf  Remaining: ['Geoff', 'Colin', 'David']
Reply


Possibly Related Threads…
Thread Author Replies Views Last Post
  Need to fix my brain on classes blackknite 2 1,193 May-01-2022, 12:25 PM
Last Post: ibreeden
  Back to loops question wernerwendy 1 2,861 Jun-17-2017, 10:02 PM
Last Post: ichabod801
  Question on runtime and improving nested for loops ackmondual 1 3,013 Jun-13-2017, 11:11 PM
Last Post: ichabod801

Forum Jump:

User Panel Messages

Announcements
Announcement #1 8/1/2020
Announcement #2 8/2/2020
Announcement #3 8/6/2020