Python Forum
deleting select items from a list
Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
deleting select items from a list
#1
i want to delete select items from a list, such as those which have a specific value in a dictionary. this often gets pretty ugly. maybe i want to remove any string that is all digits. the problem i typically run into is when i need to delete items from an existing list instead of just rebuilding a new one. i need to use indexes and when an item is deleted the items with higher indexes change to one lower. then i need another loop to recheck the new item at the same index. it makes for some ugly code.

different use cases also need different tests to decide if the item needs to be removed, making it tough to make a common function. does anyone know of something in Python that can make this easier or more elegant?

i don't want to show code because any example would need to have specific parts, like the different cases for which items to delete, and answers may focus on that.
Tradition is peer pressure from dead people

What do you call someone who speaks three languages? Trilingual. Two languages? Bilingual. One language? American.
Reply
#2
Process the list in reverse so the removals don't change the position of the unvisited elements.
Reply
#3
https://python-forum.io/thread-670.html Wrote:Modifying a list (or other container) while iterating over it
for laser in lasers:
    ...
    if rm:
        lasers.remove(laser)
This will cause an IndexError when you iterate over the loop as you have just removed an index from the list that you are looping over. A catch 22. You need to loop the list in order to remove, but you cannot remove from the list as you loop. This can be easily fixed by looping a copy of the list and removing from the actual list. All you have to do to loop a copy is add [:].
for laser in lasers[:]:
    ...
    if rm:
        lasers.remove(laser)
The [:] is a shallow copy. The is identical to using the copy module for copy.copy(). If you have nested structures you may want a deep copy. This you are going to need to use copy.deepcopy() See more info here
Reply
#4
Why do you want to mutate the list, anyway?
Reply
#5
(Oct-08-2021, 01:53 AM)Skaperen Wrote: different use cases also need different tests to decide if the item needs to be removed, making it tough to make a common function. does anyone know of something in Python that can make this easier or more elegant?

Yes, this is a common thing to do and hence an abstraction already exists: filter. As well as your sequence, it takes a predicate function that should return True if an item is to be kept.

>>> def is_even(x):
...     return x % 2 == 0
... 
>>> values = [1, 2, 3, 4, 5, 6]
>>> filter(is_even, values)
<filter object at 0x7f4d539e9f98>
>>> list(filter(is_even, values))
[2, 4, 6]
>>> names = ["Alice", "Bob", "Andrew", "Charlie"]
>>> list(filter(lambda name: name.startswith("A"), names))
['Alice', 'Andrew']
>>> 
If instead, you want to keep items for which a predicate is False, filterfalse in the itertools module does that.

It sounds like you'd really benefit from learning about writing programs more declaratively - Kevlin Henney has a great talk titled "Declarative thinking, declarative practice" on this kind of stuff.
Reply
#6
Can just use plain list comprehension for this clean and easy to read.
>>> names = ["Alice", "Bob", "Andrew", "Charlie"]
>>> [name for name in names if name.startswith('A')]
['Alice', 'Andrew']
Or the same with without.
names = ["Alice", "Bob", "Andrew", "Charlie"]
new_list = []
for name in names:
    if name.startswith('A'):
        new_list.append(name)

print(new_list)
Output:
['Alice', 'Andrew']
For me is making in new list like over,is the preferred way/solution over copy [:]: and reversed().
names = ["Alice", "Bob", "Andrew", "Charlie"]
for name in names[:]:
    if not name.startswith('A'):
        names.remove(name)

print(names)
Output:
['Alice', 'Andrew']
So it work fine,but remove() has to go over the whole list for every iteration
Big-O doesn't matter here when dealing with a lists with few items,but if a make a bigger list will see a difference.
import timeit

# Modify original list
remove = '''\
names = ["Alice", "Bob", "Andrew", "Charlie"] * 100
for name in names[:]:
    if not name.startswith('A'):
        names.remove(name)'''

# Make new list
list_comp = '''\
names = ["Alice", "Bob", "Andrew", "Charlie"] * 100
[name for name in names if name.startswith('A')]'''

print(timeit.Timer(stmt=remove).timeit(number=1000000))
So here use list comprehension 55-sec and remove use 6-minute.
Reply
#7
In my opinion, the list-comprehension is the cleanest solution.
If you have many conditions to fulfill, you can create a function which does the job for you.

def even(user):
    """
    True if uid is even

    This function could check more.
    Just a silly example
    """
    return user["uid"] % 2 == 0


# already existing data
data = [{"uid": num, "name": f"user_{num}"} for num in range(1, 101)]

# later the new list is assigned to the name data
data = [user for user in data if even(user)]
If you work inside a function and want to assign the new list, this will need the use of global, if the list is defined outside the function. This is not very nice. A class can solve this problem of reassigning without the use of global.

class Something:
    def __init__(self):
        self.database = [{"uid": num, "name": f"user_{num}"} for num in range(1, 101)]

    def add_user(self, uid, name):
        self.database.append({"uid": uid, "name": name})

    def delete_odd_users(self):
        self.database = [user for user in self.database if self.is_even(user)]

    def is_even(self, user):
        return user["uid"] % 2 == 0
If you're using threads, you should better use locking to prevent race conditions.
Almost dead, but too lazy to die: https://sourceserver.info
All humans together. We don't need politicians!
Reply
#8
(Oct-08-2021, 11:56 AM)ndc85430 Wrote: Why do you want to mutate the list, anyway?
to have a list of select items

and i need to do this efficiently when it is deep in nested loops in many cases i have encountered. i have found that simple actions on lists in-place tend be faster.
Tradition is peer pressure from dead people

What do you call someone who speaks three languages? Trilingual. Two languages? Bilingual. One language? American.
Reply
#9
(Oct-08-2021, 03:10 AM)bowlofred Wrote: Process the list in reverse so the removals don't change the position of the unvisited elements.
i've been thinking about that also to keep the actions simpler and faster. another thing i have bee trying is to replace de-selected items with None where i can change using the list to just ignore those.
Tradition is peer pressure from dead people

What do you call someone who speaks three languages? Trilingual. Two languages? Bilingual. One language? American.
Reply
#10
(Oct-08-2021, 05:32 AM)Yoriz Wrote:
https://python-forum.io/thread-670.html Wrote:Modifying a list (or other container) while iterating over it
for laser in lasers:
    ...
    if rm:
        lasers.remove(laser)
This will cause an IndexError when you iterate over the loop as you have just removed an index from the list that you are looping over. A catch 22. You need to loop the list in order to remove, but you cannot remove from the list as you loop. This can be easily fixed by looping a copy of the list and removing from the actual list. All you have to do to loop a copy is add [:].
for laser in lasers[:]:
    ...
    if rm:
        lasers.remove(laser)
The [:] is a shallow copy. The is identical to using the copy module for copy.copy(). If you have nested structures you may want a deep copy. This you are going to need to use copy.deepcopy() See more info here
what if i loop the list in reverse as suggested above? will i run into an index error while mutating the list that way? speaking of indexes, i didn't know i could get indexes that way (line 1 in your first box of code). i had been using len() and range().
Tradition is peer pressure from dead people

What do you call someone who speaks three languages? Trilingual. Two languages? Bilingual. One language? American.
Reply


Possibly Related Threads…
Thread Author Replies Views Last Post
  How to parse and group hierarchical list items from an unindented string in Python? ann23fr 0 94 Mar-27-2024, 01:16 PM
Last Post: ann23fr
  Why do I have to repeat items in list slices in order to make this work? Pythonica 7 1,259 May-22-2023, 10:39 PM
Last Post: ICanIBB
  Finding combinations of list of items (30 or so) LynnS 1 838 Jan-25-2023, 02:57 PM
Last Post: deanhystad
  For Word, Count in List (Counts.Items()) new_coder_231013 6 2,499 Jul-21-2022, 02:51 PM
Last Post: new_coder_231013
  How to get list of exactly 10 items? Mark17 1 2,406 May-26-2022, 01:37 PM
Last Post: Mark17
  select Eof extension files based on text list of filenames with if condition RolanRoll 1 1,475 Apr-04-2022, 09:29 PM
Last Post: Larz60+
  how to assign items from a list to a dictionary CompleteNewb 3 1,535 Mar-19-2022, 01:25 AM
Last Post: deanhystad
  Reading list items without brackets and quotes jesse68 6 4,523 Jan-14-2022, 07:07 PM
Last Post: jesse68
Question How to gather specific second-level items from a list chatguy 2 1,517 Dec-17-2021, 05:05 PM
Last Post: chatguy
  Getting All Items From A List knight2000 4 2,353 Sep-25-2021, 12:56 AM
Last Post: knight2000

Forum Jump:

User Panel Messages

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