Home > Net >  How to take an element out from a list of lists given by an input in python?
How to take an element out from a list of lists given by an input in python?

Time:10-16

this is my very first post and I have minimal if none experience in programming, but I started this course and now I have an exam.

I'm trying to understand how to remove an element from a list of lists given by an input.

M = ['14','15','17','18','19']
Tu = ['15','16','18']
W = ['13','14','19']
Th = ['16','17','18']
F = ['16','17','18']
days = [M, Tu, W, Th, F]


time = input('Enter time: ') 
day = input('Enter a day: ')

I would like to be able to remove '15' for example from the list M, but I can't understand first how to assign one of those lists to the input of the user, and then remove the item.

for example:

'Enter a time: 15'
'Enter a day: Monday'

How would I assign the input 'Monday' to the first list 'M' present in 'days' and remove '15' from it?

I hope I was clear, and thank you to anyone who can help.

CodePudding user response:

With lists you can just call .remove() and it'll do what you want. So

M = ['14','15','17','18','19']
M.remove('14') # M = ['15', '17', '18', '19']

Now all that's left is to somehow select the right day. To do that I'd suggest packing all lists into a dictionary instead. Like so

days = {'Monday': M, 'Tuesday': Tu, 'Wednesday': W, 'Thursday': Th, 'Friday': F}

Now you're ready to get the users input and handle it.

print(days)
time = input('Enter time: ')
day = input('Enter a day: ') 

days[day].remove(time)
print(days)    

CodePudding user response:

If you dont need to use a list specifically for days, you can use a dict instead. It'l look something like this.

M = ['14','15','17','18','19']
Tu = ['15','16','18']
W = ['13','14','19']
Th = ['16','17','18']
F = ['16','17','18']
#days = [M, Tu, W, Th, F]
days = {
    'Monday': M,
    'Tuesday': Tu,
    'Wedensday': W,
    'Thursday': Th,
    'Friday': F
    }

time = input('Enter time: ') 
day = input('Enter a day: ')

if day in days:
    if time in days[day]:
        days[day].remove(time)
        
        print(days[day])
  • Related