[Tutor] removing items from list

Alan Gauld alan.gauld at yahoo.co.uk
Mon Feb 7 05:21:08 EST 2022


On 07/02/2022 09:21, marcus.luetolf at bluewin.ch wrote:
> 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.

> 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 ']

There's a missing quote in both lists.
Please cut n paste actual code, don't re-type it.

> 
> for player in all_items:

You never use player?

>     if item in all_items:    

You don't have anything called item

>         c_all_items.remove(item)

You don't have anything called c_all_items

>         c_all_items = all_items

But you do now...

>         print(item, c_all_items)

> I'd appreciate to learn my mistake, thank you.

When posting please always include any error messages in full.
You must have had errors trying to run that code!

However, lets try to clarify your assignment.
You just want to produce N lists of N-1 items?
It doesn't matter which item gets removed? Is that right?

If so its easier to just remove the last item N times.
Something like(untested):

new_lists = []
for n in range(len(all_items)):
    newlists.append(all_items[:])  # [:] takes a copy
    del(all_items[-1])   # the last item
print(new_lists)


You can do it even more concisely using slicing but I
don't know if you covered that yet.

-- 
Alan G
Author of the Learn to Program web site
http://www.alan-g.me.uk/
http://www.amazon.com/author/alan_gauld
Follow my photo-blog on Flickr at:
http://www.flickr.com/photos/alangauldphotos




More information about the Tutor mailing list