-1

for a list, I am going to remove third item, 6th item,9th item,a and so on.
For example for the following list, I am going to remove item 30 and 60. to summarize, How I can locate multiples of 3 in a list and remove them? This is my code:

comments = [80,20,30,40,50,60]

 A = [comments.pop(i) for i, item in enumerate(comments) if i % 3 == 2]
print A

I have two problems: first, A just include 30

[30]

second, I do not know how to subtract A from comments in python.
please help, thank you !

Mary
  • 1,142
  • 1
  • 16
  • 37
  • What is the output that you are expecting? – Rajesh Yogeshwar May 31 '16 at 04:59
  • 1
    Could you provide some details about the process of removing 30 and 60? On what conditions? (if not you could just `.remove()` it) – Moon Cheesez May 31 '16 at 05:03
  • To extension to @MoonCheesez comment, what is the criteria there of just removing 30,60 – Rajesh Yogeshwar May 31 '16 at 05:05
  • @ Rajesh and @Moon Thanks ! I have some lists that I do not want third, sixth, 9th, 12th items. Size of the lists are different. Thats why I decided to use the code "A = [comments.pop(i) for i, item in enumerate(comments) if i % 3 == 2]", however the code can not capture the sixth element. Please let me know if you need more information. Thanks ! – Mary May 31 '16 at 13:50

1 Answers1

1

comments = [80,20,30,40,50,60]

If you would like to remove elements eg. 30 and 60

remove_list = [30, 60]

for remove_value in remove_list:
    comments.remove(remove_value)

print(comments)

[80, 20, 40, 50]

Edit:

remove_index = []

for remove_value in remove_list:
    remove_index.append(comments.index(remove_value))

for remove_value in remove_list:
    comments.remove(remove_value)

I don't no of a more elegant way to avoid 2 for loops

EDWhyte
  • 333
  • 3
  • 15
  • @Thanks EdWhyte, the problem is: I should locate item 3, item 6, item 9, item 12, and so on at first and then remove them. , can you tell me how I can locate kite items in a list – Mary May 31 '16 at 10:10
  • @Mary I added a for loop to locate the indices before they are removed – EDWhyte May 31 '16 at 12:07
  • thanks! The problem is that I do not know what is the value in the 3th, 6th, 12th,... in the list. In addition, I do not know the length of the list. Thats why I though I should use the following code: "A = [comments.pop(i) for i, item in enumerate(comments) if i % 3 == 2]". However, it could not capture 6th item. – Mary May 31 '16 at 13:59
  • @Mary I am starting to understand your problem now. So you want the store these values and want to remove these values for _indices_ 3, 6, 12. Just to clarify, indices start at 0 so for a `list = [1, 2, 3, 4]` list index 0 will give `list[0] = 1`. If you say item 3 (index 3) is this the third element `l[2] = 3` or the third index `l[3] = 4`? – EDWhyte May 31 '16 at 15:54