How to modify list while iterating?

+1 vote

I want to loop over items so that I can skip an item while looping, and the below shown code does not  give expected output.

l  = range(100)                         
for i in l:                         
    print i,                         
    print l.pop(0),                  
    print l.pop(0)
Jul 4, 2019 in Python by Shabnam
• 920 points

edited Jul 5, 2019 by Kalgi 46 views

1 answer to this question.

0 votes

Hi,

You can try slice operator mylist[::3] to skip across to every third item in your list.

mylist = [i for i in range(100)]
for i in mylist[::3]:
  print(i)
answered Jul 5, 2019 by Taj
• 1,040 points

Related Questions In Python

+2 votes
11 answers
0 votes
1 answer

How to sort a list of strings?

Basic answer: mylist = ["b", "C", "A"] mylist.sort() This modifies ...READ MORE

answered Jun 4, 2018 in Python by Aryya
• 7,350 points
74 views
0 votes
1 answer

How to sort a list of strings?

Try  items = ["live", "like", "code", "cool", "bug"] ...READ MORE

answered Jul 27, 2018 in Python by Priyaj
• 57,510 points
36 views
0 votes
1 answer

How to split a string into a list?

You can use the function  text.split() This should be ...READ MORE

answered Jul 30, 2018 in Python by Priyaj
• 57,510 points
88 views
0 votes
1 answer
+1 vote
2 answers

how can i count the items in a list?

Syntax :            list. count(value) Code: colors = ['red', 'green', ...READ MORE

answered Jul 6, 2019 in Python by Neha
• 330 points

edited Jul 8, 2019 by Kalgi 546 views
0 votes
0 answers
+4 votes
6 answers
+1 vote
1 answer

How can I reverse list in Python?

Reversing a list is a commonly used ...READ MORE

answered May 13, 2019 in Python by Taj
• 1,040 points
64 views
0 votes
1 answer

How to put time delay in Python?

You can use sleep() method to sleep ...READ MORE

answered May 28, 2019 in Python by Taj
• 1,040 points
45 views