Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python Remove All Elements in List Before Specific Element

Tags:

python

I have a list that I am using to process a series of tasks on directories. Occasionally the process will get stuck at a certain directory. Currently I'm removing that element and re-running the process thru the list. However, this is getting to take a while.

Here's what I'm doing now:

directories = next(os.walk('/home'))[1]
directories.remove('brokendirectory')
process_directory(directory)

What I'd like to do is to remove EVERY directory INCLUDING the directory that's broken and only work on the list of directories after that broken directory. Something like this:

def clear_list(directories, element):
  new_list = []
  for directory in directories:
    if directory == element:
        break
    else:
        new_list.append(directory)
  return(new_list)

directories = next(os.walk('/home'))[1]
new_directories = clear_list(directories,'brokendirectory')
process_directory(new_directories)

Obviously my function does not work as-is.

How can I remove all elements in the list including the one specified and return a new list for processing?

like image 458
Ken J Avatar asked Jan 25 '19 15:01

Ken J


3 Answers

You can use index method of the the list to find the index of the element you want and then use a slice to remove all elements up to and including it.

directories = directories[directories.index('brokendirectory')+1:]
like image 134
fstop_22 Avatar answered Nov 05 '22 20:11

fstop_22


You can use the function dropwhile:

from itertools import dropwhile

l = 'ABCDEFG'
element = 'D'

list(dropwhile(lambda x: x != element, l))

# ['D', 'E', 'F', 'G']
like image 38
Mykola Zotko Avatar answered Nov 05 '22 19:11

Mykola Zotko


Find the index of the broken directory:

idx = directories.index('brokendirectory')

Use that index to slice a new list:

new_directories = directories[idx+1:]

Then process that:

process_directory(new_directories)
like image 27
TigerhawkT3 Avatar answered Nov 05 '22 20:11

TigerhawkT3