-1

Desired output 1:

Let's say I have a list like this:

my_list = ['car', 'car', 'truck', 'van', 'car', 'truck', 'van']

I have three cars, two vans and two trucks. Is there a way to print the output of the items of the list like this:

3 cars
2 trucks
2 vans

Desired output 2:

And is there another method to remove the number of cars the user says like:

How many cars do you want to remove?: 2
1 car
2 trucks
2 vans

These are my questions. How can I do this in Python using the least amount of code?

I agree there is a duplicate of this question but those don't explain how I can delete the items from my list upon user input.

OldWizard007
  • 370
  • 1
  • 8
  • Use a dictionary to store occurrences of each vehicle and a for loop iterating on your list to increment these occurrences. – qouify Apr 03 '21 at 18:44
  • how can I do it? @qouify – OldWizard007 Apr 03 '21 at 18:45
  • Partial duplicate: [How can I count the occurrences of a list item?](https://stackoverflow.com/questions/2600191/how-can-i-count-the-occurrences-of-a-list-item) Once you have a `Counter`, you can simply subtract. – wjandrea Apr 03 '21 at 19:23

2 Answers2

3

Question 1:

You can use Counter to achieve this:

from collections import Counter

my_list = ['car', 'car', 'truck', 'van', 'car', 'truck', 'van']
count_dict = Counter(my_list)  # Return a dictionary

for key, value in count_dict.items():
    print(value, key)

Output:

3 car
2 truck
2 van

Question 2:

You can pass the remove function in a loop:

number_of_occurances = 1
string_to_remove = 'car'

for number in range(number_of_occurances):
    my_list.remove(string_to_remove)
    
print(my_list)

Output:

['car', 'truck', 'van', 'car', 'truck', 'van']
wjandrea
  • 28,235
  • 9
  • 60
  • 81
GTS
  • 56
  • 6
2

Desired output 1:

the list method, a simple way to look into it is the .count()

try it out here i.e

cars-count = my_list.count("car")

Desired output 2:

Do you want the list updated when you run the remove items? or just the values?

i.e when you run How many cars do you want to remove?: 1, the list will look like this

my_list = ['car', 'truck', 'van', 'car', 'truck', 'van']
wjandrea
  • 28,235
  • 9
  • 60
  • 81
twoscoops
  • 29
  • 2
  • Yes, I do want the list updated. @twoscoops – OldWizard007 Apr 03 '21 at 18:52
  • `cars-count` is an invalid variable name – wjandrea Apr 03 '21 at 19:03
  • For part 2, this does not answer the question. Once you have enough [reputation](/help/reputation), you'll be able to leave comments on posts to ask for clarification. BTW, welcome to SO! Please take the [tour], and check out [answer] if you want more tips. – wjandrea Apr 03 '21 at 19:06