[Tutor] removing items from list

Dennis Lee Bieber wlfraed at ix.netcom.com
Mon Feb 7 12:20:19 EST 2022


On Mon, 7 Feb 2022 10:21:45 +0100, <marcus.luetolf at bluewin.ch> declaimed
the following:

>Hello Experts,
>
>of a list of n items at each of n iterations one other item should be
>removed.
>
>The result should yield n lists consisting of n-1 items.
>
>Even using a copy oft he list  the indexing got mixed up.  
>
> 
>
>My last attempt:
>
> 
>
>all_items = ['item1 ','item2 ', item3 ',' item4 ', 'item5 ','item6 ',
>'item7', 'item8', 'item9', 'item10 ']
>
> 
>
>copy_all_items = ['item1 ','item2 ', item3 ',' item4 ', 'item5 ','item6 ',
>'item7', 'item8', 'item9', 'item10 ']
>
> 
>
>for player in all_items:
>
>    if item in all_items:    

	Where did "item" come from? Did you mean "player"?

	This is a tautology -- since the for loop extracts one item from the
list, then by definition, that item is IN the list.

>
>        c_all_items.remove(item)

	Where did "c_all_items' come from? {I'll be kind and assume you meant
the "copy_all_items" from above}

>
>        c_all_items = all_items

	You've just replaced the list you removed an item from, with a
reference to the original (full list) list so further loop cycles will be
removing items from the full list... THAT is a major NO-NO when iterating
over a list (the list is getting shorter, but the iteration is advancing --
so you skip over entries).




>>> from itertools import combinations
>>> itemList = ["item1", "item2", "item3", "item4",
... 		"item5", "item6", "item7", "item8",
... 		"item9", "item0"]
>>> results = combinations(itemList, len(itemList) - 1)
>>> for res in results:
... 	print(res)
... 
('item1', 'item2', 'item3', 'item4', 'item5', 'item6', 'item7', 'item8',
'item9')
('item1', 'item2', 'item3', 'item4', 'item5', 'item6', 'item7', 'item8',
'item0')
('item1', 'item2', 'item3', 'item4', 'item5', 'item6', 'item7', 'item9',
'item0')
('item1', 'item2', 'item3', 'item4', 'item5', 'item6', 'item8', 'item9',
'item0')
('item1', 'item2', 'item3', 'item4', 'item5', 'item7', 'item8', 'item9',
'item0')
('item1', 'item2', 'item3', 'item4', 'item6', 'item7', 'item8', 'item9',
'item0')
('item1', 'item2', 'item3', 'item5', 'item6', 'item7', 'item8', 'item9',
'item0')
('item1', 'item2', 'item4', 'item5', 'item6', 'item7', 'item8', 'item9',
'item0')
('item1', 'item3', 'item4', 'item5', 'item6', 'item7', 'item8', 'item9',
'item0')
('item2', 'item3', 'item4', 'item5', 'item6', 'item7', 'item8', 'item9',
'item0')
>>> 


-- 
	Wulfraed                 Dennis Lee Bieber         AF6VN
	wlfraed at ix.netcom.com    http://wlfraed.microdiversity.freeddns.org/



More information about the Tutor mailing list