Question

How do you remove an element in python?

No correct solution

OTHER TIPS

If you want to delete an item at an index from a list,

Given dropped_class is an integer and 0 <= dropped_class < len(list1) and list1 is a list

del list1[dropped_class]

or

list1.pop(dropped_class)

or if you know only the item but not the index you can do

list1.remove(item)

your code is wrong in many ways, and you should definitely get through it with a knowledgeable friend. About your specific problem:

dropped_class = raw_input ("Which class would you like to drop? Enter number corresponding to class name: ")
del dropped_class

what do you expect it to do? you create the variable dropped_class, which contains a string, and then you delete that variable's value. What it does in the end? Nothing. Coding is no magic, you can't write anything that has no meaning and expect that to work! My best advice to you is:

  1. think
  2. think again
  3. code

so basically, what you want is:

  1. get the name of the class to be removed
  2. check whether that class' name exists
  3. remove it from the lists

so in code that becomes:

# 1. get the name of the class to be removed
dropped_class = raw_input ("Which class would you like to drop? Enter number corresponding to class ")
# 2. check whether that class' name exists
found = False
for class_tup in tup5:
    if dropped_class in class_tup[0]:
        found = True
        break
# 3. remove it from the lists
if found:
    tup5.remove(class_tup)

there are better, shorter ways to do it, but I'm giving you that way of doing it so it is more readable and understandable for a beginner.

Edit:

the following code:

if dropped_class in class_tup[0]:

checks if the string within dropped_class is a sub string of the string being the first element of class_tup. You can check for exact equality with:

if dropped_class == class_tup[0]:

Nota Bene:

  • the naming of your class tuples is really wrong, you should declare something like:

    classes = [('Math 101', 'Algebra', 'Fall 2013', 'A'), ('History 201', 'WorldWarII', 'Fall 2013', 'B'), ('Science 301', 'Physics', 'Fall 2013', 'C'), ('English 401', 'Shakespeare', 'Fall 2013', 'D')]

  • the way you store your classes is also pretty wrong, you might want to separate the first field to have Math and 101 separated and easily searchable (give all 101 courses or give all level courses and topics for Math…), that will make it easier as well when you'll refactor your code to put it in a database.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top