Python Forum
Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
list loop and drop
#1
Hi,

I have a list and I loop it:
grab first item and do something with each item in the list
after that is done: no more need for first item.

grab second item and do something with each remaining item in the list
after that is done: no more need for second item.

etc

To visualize it:
[1,2,3,4,5]

1 will do something with 2,3,4,5 .... and drops 1
now the list is 2,3,4,5
2 will do something with 3,4,5 .... and drops 2
now the list is 3,4,5

itertool combinations makes a new list with all the unique combinations. Which kinda is what I'm doing HOWEVER given a list of thousands+ I THINK it's faster to yield the original list and somehow drop used item.


Makes sense? Curious how to do this.
Reply
#2
I imagine someone else can do it in one line, but here's what I thought up, and it works.

list_of_items = [1, 2, 3, 4, 5]

work_list = list_of_items.copy()

del work_list[0]
for item in list_of_items:
    try:
        print(sum(work_list))
        del work_list[0]
        
    except IndexError:
        print("Done")
        
Reply


Possibly Related Threads…
Thread Author Replies Views Last Post
  Appending to list of list in For loop nico_mnbl 2 2,331 Sep-25-2020, 04:09 PM
Last Post: nico_mnbl
  Append list into list within a for loop rama27 2 2,313 Jul-21-2020, 04:49 AM
Last Post: deanhystad
  loop through list or double loop 3Pinter 4 3,388 Dec-05-2018, 06:17 AM
Last Post: 3Pinter
  Write a for loop on list of lists without changing the shape of the main list Antonio 3 3,719 Jun-19-2018, 02:16 AM
Last Post: ichabod801
  For looping over a list, editing the list from inside the loop? Krookroo 3 3,895 Sep-04-2017, 05:08 PM
Last Post: Krookroo
  How to change from printFacts ( ) to return a list & Loop over list when writing CSV Ivan1 14 8,154 Aug-30-2017, 12:14 PM
Last Post: metulburr

Forum Jump:

User Panel Messages

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