Home > Software engineering >  Deleting list element after use
Deleting list element after use

Time:02-26

s = []
seats = [4,1,5,9]
students = [1,3,2,6]
for i in range(len(students)):
    s.append((min(seats, key=lambda x:abs(x-students[i]))))
print(s)

Returns minimum distance for each of our student values. I want to delete the seat from use after a student is allocated it. How would I perform that?

CodePudding user response:

Use list.remove with the last value of s

for i in range(len(students)):
    s.append(min(seats, key=lambda x: abs(x - students[i])))
    seats.remove(s[-1])

CodePudding user response:

If you want to remove the last item from a list I can think of two ways:

1)

mylist = mylist[:-1]

This is fine even if the original list is empty. However, it does mean that a new copy of the list has to be created and that could have a negative impact on memory usage.

2)

if mylist:
  mylist.pop(-1)

This will remove the last entry in the list in situ. You do however need to check to ensure that there is at least something in the list

CodePudding user response:

Like this?

seats = set([4,1,5,9])
students = [1,3,2,6]

result = []
for student in students:
    seat = min(seats, key=lambda seat:abs(seat-student))
    seats.remove(seat)
    result.append(seat)

print(result)
  • Related