Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python Remove Item from list

Tags:

python

I'm really new to Python, only working on it, as another guy in my team left and need to get some work over the line, so apologies if this is a stupid question.

I need to remove items from a list (they'll contain a certain phrase) and have googled and tried a few ways but it doesn't seem to be working.

What I've currently got is,

def get_and_count_card_files(date):
    # Retrieve the DC and SD card files
    dc_files = dc_card_files.get_dc_files(dc_start_location, date)
    sd_files = sd_card_files.get_sd_files(sd_start_location)
    print(dc_files)

if '*NoCover*' in dc_files:
    dc_files.remove('*NoCover*')

Dc_files being the list (bunch of file names) and I need to remove anything that has NoCover in the file name. It does exist as the print function shows me it does.

Anyone any idea what I'm doing wrong

enter image description here

like image 826
titan31 Avatar asked Sep 21 '15 10:09

titan31


1 Answers

With this piece of code, the * won't do a glob or regular expression in these contexts:

if '*NoCover*' in dc_files:
    dc_files.remove('*NoCover*')

so it would be better to say:

if 'NoCover' in dc_files:

However, we then have to find the right entry to remove in the list, without using wildcards.

For a small list, you could iterate over it. A list comprehension would do:

new_dc_files = [dc for dc in dc_files if 'NoCover' not in dc]

It's a compact way of saying:

new_dc_files = list()
for dc in dc_files:
    if 'NoCover' in dc:
         continue
    new_dc_files.append(dc)
like image 120
Simon Fraser Avatar answered Sep 18 '22 01:09

Simon Fraser