How do I make the for loop use a new list that was made with the if statement

Viewed 34

This is my code:

the_list = ['Lily', 'Brad', 'Fatima', 'Zining']

for name in the_list:
    print(name)
    if name == 'Brad':
      the_list = ['Tom', 'Jim', 'Garry', 'Steve']
    else:
      continue

How do I make it so that the for loop now runs through the new list

I know I could just make a new for loop in the if statement but that's not what i want it to do.

1 Answers

Use a recursive function:

def check_the_list(x):
    for name in x:
        print(name)
        if name == 'Brad':
            check_the_list(['Tom', 'Jim', 'Garry', 'Steve'])
        else:
            continue


the_list = ['Lily', 'Brad', 'Fatima', 'Zining']

check_the_list(the_list)

OUT: Lily Brad Tom Jim Garry Steve Fatima Zining

Or stopping after checking the other list:

def check_the_list(x):
    for name in x:
        print(name)
        if name == 'Brad':
            check_the_list(['Tom', 'Jim', 'Garry', 'Steve'])
            break
        else:
            continue


the_list = ['Lily', 'Brad', 'Fatima', 'Zining']

check_the_list(the_list)

OUT: Lily Brad Tom Jim Garry Steve

Related