8.13 LAB: Elements in a range

Question:

I have this code:

input_numbers = [int(x) for x in input().split(' ')]
input_range = [int(x) for x in input().split(' ')]

for number in input_numbers:
    if input_range[0] <= number <= input_range[1]:
        print('{}'.format(number), end = ' ')

It should read in two lists of numbers, (where the second list has two values representing a range), and then print numbers from the first list that are between the two numbers in the second list. I want to print all these values with commas after each (including after the last one).

For example, if I input 25 51 0 200 33 and then 0 50, the output should be 25,0,33,.

However, I currently get 25 0 33 instead. How can I fix it so that the commas are printed?

Answers:

There are two simple ways to solve this:

  • Use end=',' in your print statement, as suggested by @unmitigated
  • Use the comma inside string to be printed and set end='' so that there is no separation space:
    print('{},'.format(number), end = '')

This is beyond your original question but should always give input() a string to inform the user what is being requested from them. In your example,

input_numbers = [int(x) for x in input('Input numbers: ').split(' ')]
input_range = [int(x) for x in input('Input range: ').split(' ')]

Also, in Python there is another way to do the filtering using a list comprehension. The code is actually uglier and wouldn’t make sense to use it in this case, but I’m including it for reference anyway. One

print(','.join([str(n) for n in input_numbers
                if input_range[0] <= number <= input_range[1]] + ',', end='')

(The + ',' and end='' are needed because the problem statement explicitly said, respectively, to "follow each output integer by a comma, even the last one" and to "not end with newline".)

Answered By: ATony
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.