Home > Mobile >  Python continue and break usage
Python continue and break usage

Time:09-15

I need to solve the following problem and I assume I have to use continue and break logic.

  • I have to create an empty to do list and iterate over the dictionary of tasks. I need to add tasks that contain the substring "organize" and once the length of the to do list reaches 2 tasks I break the loop. *
tasks = {
    0 : ['Reorganize the cabinet'],
    1 : ['Give the dog a bath', 'Create a twitter thread'],
    2 : ['Learn python dictionary'],
    3 : ['Take a walk'], 
    4 : ['Go grocery shopping'], 
    5 : ['Update Facebook'],
    6 : ['Respond to emails'],
    7 : ['Walk the dog']
}

I could solve the second part of adding the tasks that contain the substring "organize" and could iterate through the length of tasks to filter tasks that are not more than 2. Yet, I can't find the way how to combine two conditions into one.

CodePudding user response:

Put an if statement in the loop that checks the length of the to do list, and breaks out of the loop when it reaches 2.

todo_list = []
for task in tasks.values():
    if 'organize' in task:
        todo_list.append(task)
    if len(todo_list) == 2:
        break

CodePudding user response:

does this do the job:

to_do_list = []
for key, value in tasks.items():
    to_do_list.append([val for val in value if 'organize' in val])
    if len(to_do_list) == 2:
        break

If you want a flattened list of items, replace to_do_list.append with to_do_list.extend

  • Related