beginner
beginner

Reputation: 3

How to show how many objects in the list, with inputting of list name and object?

I want to write a program that shows the count of particular objects in particular list. The user inputs a list name, then inputs the object, then gets the count.

Here is my code:

list_1 = [1, 2, 4, 2, 5, 6, 7, 3, 5, 6, 3, 2, 1, 7, 8, 9, 3, 6, 5, 3, 4]

list_2 = [12, 14, 13 , 11, 16, 15, 17, 18, 18, 19, 17, 15, 19, 11, 12, 14, 13]

def count_objects(wlist):    
    read_o = int(input("input object: "))
    print(wlist.count(read_o))

getList = input("input list: ")
count_objects(getList)

But it says:

Traceback (most recent call last):
 line 6, in <module>
    count(wlist)
  line 4, in count
    print(wlist.count(read_o))
TypeError: must be str, not int 

Upvotes: 0

Views: 60

Answers (1)

Will Da Silva
Will Da Silva

Reputation: 7040

As Juanpa Arrivillaga commented:

The fundamental problem here is that you are relying on the variable name.

You should probably use a dictionary instead, if you want to map user inputs to some pre-defined values within your program. That can be done like this:

lists = {
    # These keys can be whatever you want
    '1': [1, 2, 4, 2, 5, 6, 7, 3, 5, 6, 3, 2, 1, 7, 8, 9, 3, 6, 5, 3, 4],
    '2': [12, 14, 13 , 11, 16, 15, 17, 18, 18, 19, 17, 15, 19, 11, 12, 14, 13],
}

def count_objects(wlist):    
    read_o = int(input("input object: "))
    print(wlist.count(read_o))

getList = input(f"input list: (valid inputs are: {list(lists)})\n")
count_objects(lists[getList])

This is a very minimal edit of your code, which could stand to be improved quite a bit. Once you have it working I would recommend heading over to https://codereview.stackexchange.com to get feedback.

If you really want to access a variable in your code using user input, you can use eval for that, but I strong recommend against it. A slightly better approach is to look it up in the globals() or locals() dicts, but even then you'd still be misusing variables.

Upvotes: 2

Related Questions