3

Is there any way to do this in a single line, but without using a 'None'?:

folders = ['Project 1', 'Project 2']
files = os.listdir('/home/user/Documents/Python')
for i in files:
    files.remove(i) if i in folders else None

Could one 'skip' the 'else' statement?

Thanks in advance.

4
  • 4
    You should do files = [_ for _ in files if _ not in folders], the Python style. Commented May 25, 2017 at 17:47
  • 1
    @zyxue: _ is only for unused variables. Commented May 25, 2017 at 18:04
  • 1
    @zyxue don't use _ unless it is a throwaway variable, which it is not. Commented May 25, 2017 at 18:04
  • In this case, it is a throwaway as it won't be needed out of the list comprehension, no? Commented May 25, 2017 at 18:05

1 Answer 1

12

if i in files: files.remove(i)

Sign up to request clarification or add additional context in comments.

1 Comment

Note: but this isn't the recommended style. Better split into two lines.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.