Python nested for loops

advertisements
car_list=[['BMW',4,False,200],['Mercedes',3,False,250],['Renault',2,False,150],['Audi',3,False,180]] #car list

new_list=[]
def add_new_car(horsepower,brand,car_list):
    for lists in car_list:
        for i in lists:
            if brand==i :
                lists[1]=lists[1]+1
                print(car_list)

            else: #from there i dont want to execute program when brand is mercedes. if brand is different from list i want to execute . but program executes.:$$
                if brand != i:
                    new_list.append(brand)
                    new_list.append(1)
                    new_list.append(True)
                    new_list.append(horsepower)
                    car_list.append(new_list)
                    print(car_list)
                    break
        break

brand='Mercedes' #when brand is mercedes program executes else if part and creates new list and add this lst to car list. but i cant add it to existed mercedes list as> mercedes,3,false,250
horsepower=170

add_new_car(horsepower,brand,car_list)

My code is not working as I want it to. I can't do the thing when the brand is mercedes it executes the else if part and creates new list.. but i want to add it to existing mercedes list.. and new list will be

[['BMW',4,False,200],['Mercedes',4,False,250],['Renault',2,False,150],['Audi',3,False,180]]

not

[['BMW', 4, False, 200], ['Mercedes', 3, False, 250], ['Renault', 2, False, 150], ['Audi', 3, False, 180], ['Mercedes', 1, True, 170]]

what can i do for it?


This code works for you ─░layda. You do not need to add inner for loop and putting else after for loop guarantees to add new item if there is no match.

car_list = [['BMW', 4, False, 200], ['Mercedes', 3, False, 250], ['Renault', 2, False, 150], ['Audi', 3, False, 180]]

def add_new_car(horsepower, brand, car_list):
    for lists in car_list:
        if lists[0] == brand:
            lists[1] += 1
            break
    else:
        new_list = []
        new_list.append(brand)
        new_list.append(1)
        new_list.append(True)
        new_list.append(horsepower)
        car_list.append(new_list)

brand = 'Mercedes'
horsepower = 170

add_new_car(horsepower, brand, car_list)
print car_list