Trying to loop through a list in python and see i can match a 1 or 0 and return the value of that index location

Viewed 36

sample list [1, 0, 0, 1, 0, 0, 1, 0, 0, 0]

1 means occupied and 0 means unoccupied

expected output: occupied [0,3,6] unoccupied: [1,2,3,4,5,6,7,9]

def row_seats(seats):
occupied_seats =[]
vacant_seats =[]
for x in seats:
    if x == 0:
        vacant_seat.index(x)
    elif x == 1 :
        occupied_seats.index(x)

this is what i have done so far but i do not think i am approaching it properly any help would be appreciated!

1 Answers

You need to use enumerate to access the correct index,

def row_seats(seats):
    occupied_seats =[]
    vacant_seats =[]

    for ind, x in enumerate(seats):
        if x == 0:
            vacant_seats.append(ind)
        elif x == 1 :
            occupied_seats.append(ind)

    return vacant_seats, occupied_seats


seat_list = [1, 0, 0, 1, 0, 0, 1, 0, 0, 0]

vacant, occupied = row_seats(seat_list)

print(vacant)
print(occupied)

The original vacant_seat.index(x) was wrong because it was trying to search for x in an empty list. The correct approach appends the index to the respective lists.

Using index was also incorrect. Even if used properly (on the original - input list, with appending), you were obtaining an index of either 0 or 1. This would persistently return the index of only the first occurrence of those values.

Related