how can I count every item in a list by a specific range? Also, why the last item in my output is not sorted?

Question:

I have written a code to receive the user input as a list.

def lst_data():
    lst = []
    total = int(input('Number of Data: '))
    for number in range(0, total):
        user_data = int(input('Enter the Data: '))
        lst.sort()
        lst.append(user_data)
    print(lst)

the output is:

[50, 51, 52, 53, 54, 55, 57, 58, 59, 60, 61, 62, 63, 64, 65, 68, 70, 70, 71, 72, 73, 74, 75, 76, 77, 79, 79, 80, 80, 81, 82, 84, 86, 87, 88, 89, 89, 90, 91, 83]

The next step I want to do is count every item on that list by every 6 numbers like 50-55 = ???, 56-61 = ???, 62-67 =???, and so on.

I’ve been trying with:

counter =  0
for i in last:
    if 50 < i < 55:
    counter += 1

print(counter)

it works but I have to repeat the code over and over and value in the "if statement" has to be from the user input

how can i figure this out? and I want to check if there is any way to make my code simpler

Asked By: roso

||

Answers:

You are first sorting then adding the element, so in your loop sorting is done first and then the last element is added. Hence its left out. So you can swap the lines like below.

Your code

def lst_data():
    lst = []
    total = int(input('Number of Data: '))
    for number in range(0, total):
        user_data = int(input('Enter the Data: '))
        # First append
        lst.append(user_data)
        # Then sort
        lst.sort()
    print(lst)

Suggested code

Below is the code with list comprehension.

  1. loop interates over the total to take that many number of inputs
  2. The values are then added to the list.
  3. The list is then sorted out and printed
def lst_data():
    lst = []
    total = int(input('Number of Data: '))
    lst = sorted([int(input('Enter the Data: ')) for i in range(total)])
    print(lst)     
Answered By: Abhi
def lst_data():
lst = []
total = int(input('Number of Data: '))
for number in range(0, total):
    user_data = int(input('Enter the Data: '))
    lst.append(user_data)
    lst.sort()
print(lst)

use this code

Answered By: alirah75

I think this is what you’re trying to do:

def count(lo, hi, _list):
    return sum(lo <= e <= hi for e in _list)

nd = int(input('Number of data items: '))
data = []

for _ in range(nd):
    datum = int(input('Enter datum: '))
    data.append(datum)

lo = int(input('Enter low range value: '))
hi = int(input('Enter high range value: '))

print(f'There are {count(lo, hi, data)} items in the range {lo}-{hi}')

Example:

Number of data items: 5
Enter datum: 2
Enter datum: 1
Enter datum: 3
Enter datum: 5
Enter datum: 6
Enter low range value: 1
Enter high range value: 5
There are 4 items in the range 1-5

Note:

There is no reason to sort the list

Answered By: OldBill
Categories: questions Tags: , , , ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.