-3

I have this simple code

all_rooms have 20+ elements

del all_rooms[0]
del all_rooms[1]
for everyRoom in all_rooms:
    print(everyRoom)

I get this error

del all_rooms[0]
IndexError: list assignment index out of range

I just want to remove the 0th and 1st index from list.

I saw an answer from here on SO

I can print my list elements easily if I comment out del statements

Community
  • 1
  • 1
Umair Ayub
  • 19,358
  • 14
  • 72
  • 146
  • Use pop(0) and pop(1). – Katpoes Jan 21 '15 at 09:19
  • 1
    Can you include content of `all_rooms` list in your question. – Tanveer Alam Jan 21 '15 at 09:19
  • 1
    `del` should also work :) – Umair Ayub Jan 21 '15 at 09:19
  • Why not: `all_rooms[:] = all_rooms[2:]` ? – Jon Clements Jan 21 '15 at 09:21
  • 3
    Note that you probably want to `del all_rooms[1]` before `del all_rooms[0]` (since after deleting 0th, 1st will become 0th) – fredtantini Jan 21 '15 at 09:23
  • 1
    @fredtantini But `all_rooms` content more than 20 elements. So `del all_rooms[0]` then `del all_rooms[1]` should not give `IndexError` ryt ? – Tanveer Alam Jan 21 '15 at 09:25
  • @TanveerAlam I don't know why the `IndexError` occurs, just that if you want to del/pop the first 2, you should begin to del the second before the first. (or pop/del the index 0 twice). – fredtantini Jan 21 '15 at 09:28
  • 1
    @Umair : can you please add to your question evidence that `all_rooms` contains at least 3 elements. I'd like to know why `del all_rooms[0]` isn't working because, unless the list is empty, it should. – mhawke Jan 21 '15 at 09:36
  • 2
    `I just want to remove the 0th and 1st index from list.` your desire and the answer that you accepted are irrelevant. So better you make your question clear. – GLHF Jan 21 '15 at 09:38
  • @howaboutNO Instead of deleting, I would prefer that approach ... that yields to the results as I want – Umair Ayub Jan 21 '15 at 09:39

2 Answers2

0

Instead of using del - use slicing and replace the contents of all_rooms with the 3rd element onwards.

all_rooms[:] = all_rooms[2:]
Jon Clements
  • 138,671
  • 33
  • 247
  • 280
0

Try using :

for everyRoom in all_rooms[2:]:
    print(everyRoom)

This is known as list slicing, where you give a starting and ending position, leaving the ending position blank we can say that the python automatically takes the len(list) as ending position , so using all_rooms[2:len(everyRoom)] will also yield same results.

ZdaR
  • 22,343
  • 7
  • 66
  • 87
  • "yield same results" - unless OP actually does want to remove the items from `all_rooms` - in which case this answer is not the same. – mhawke Jan 21 '15 at 09:31
  • Thanks, Instead of deleting, I would prefer your approach ... that yields to the results as I want – Umair Ayub Jan 21 '15 at 09:33