0

>>>missions = ["MI1", "MI2", "MI3"] >>>for mission in missions [0:2]: missions.remove(mission) print(missions) ['MI2', 'MI3'] ['MI3'] ------------------------- Why is this the result?? ['MI2', 'MI3'] ['MI3'] I thought that it was saying mission was ['MI1', 'MI2'] And that after removing mission from missions we'd be left with just ['MI3'] I'm still new to Python, can you guys please help me out? Thanks!

5th Apr 2017, 11:56 PM
Dorcas_Dorcas
+ 8
đ wow, what a long title
6th Apr 2017, 5:05 AM
Agus Mei
+ 7
start => missions = ['MI1', 'MI2', 'MI3'] first loop iteration removes 'MI1' => missions =['MI2', 'MI3'] second iteration removes 'MI2' => missions = ['MI3'] last iteration removes 'MI3' => missions = [] If you want to keep 'MI3' use: for mission in missions[:-1]: # <----the difference is in here missions.remove(mission) print(missions)
6th Apr 2017, 12:15 AM
Ulisses Cruz
+ 3
A line by line rundown: 1st line: create a variable that contains a list. 2nd: create a for loop that ends when it reaches the second to last item in the list. In the for loop: 1: Remove a list item that matches what you put in the remove function. 2: Print your list If you're trying to remove all items from the list using a list slice try [:] instead of [0:2]. The second line of code is the for loop. The second line of code in the for loop prints the list. The second line in the results shows what's left in the list. Sorry if this doesn't completely clear it up. I'm a little confused by what you're looking for.
6th Apr 2017, 2:14 AM
Trevor Brick
0
I guess it may be due to you getting the entire list instead of the just the first two elements. If you want to keep MI3 you could try range(len (missions)-1) instead of missions [0:2]
6th Apr 2017, 12:17 AM
Trevor Brick
0
Sorry if your answer already explained this, but I'm still a bit confused... Isn't the second line of code telling us that mission is ['MI1', 'MI2']? Could you please help me understand why "for mission in missions[0:2]" followed by "missions.remove(mission)" causes each loop iteration to remove things in the manner you previously explained? Why didn't it remove mission=['MI1', 'MI2'] from missions=['MI1', 'MI2', 'MI3'] ?
6th Apr 2017, 12:54 AM
Dorcas_Dorcas
Hot today
XP farming