Python Forum
Help needed with lists please
Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
Help needed with lists please
#1
Hi I'm fairly new to Python, been doing some work with lists, but have got stuck. Hoping someone maybe can help.

I need to take an input list of numbers. Than print the numbers that are not in the range of 0 to 5. So any numbers that are not 0,1,2,3,4,5 will be printed as my output.


Here is what I've trailed so far, with no luck.

temperatures = [12, 4.5, -1, -3.4, 5, 6, 2]                
    
wrong_temps = []

a = 0
b = 5

for i in temperature:
    if i < a or i > b:
    wrong_temps.append(i)

print(wrong_temps)
Reply
#2
you need to indent after if:
temperatures = [12, 4.5, -1, -3.4, 5, 6, 2]                
     
wrong_temps = []
 
a = 0
b = 5
 
for i in temperature:
    if i < a or i > b:
        wrong_temps.append(i)
 
print(wrong_temps)
Reply
#3
you have it more or less right, there is error (note that the list is temperatures, temperature)
and also the indentation error on 10 (which may be because of missing python tags which I fix for you)

temperatures = [12, 4.5, -1, -3.4, 5, 6, 2]                
     
wrong_temps = []
 
a = 0
b = 5
 
for i in temperatures:
    if i < a or i > b:
        wrong_temps.append(i)
 
print(wrong_temps)
Output:
[12, -1, -3.4, 6]
If you can't explain it to a six year old, you don't understand it yourself, Albert Einstein
How to Ask Questions The Smart Way: link and another link
Create MCV example
Debug small programs

Reply
#4
I have to solution, many thanks for your help.
Reply
#5
You may also do (with more Pythonic names)
if not low <= temp <= high:
Test everything in a Python shell (iPython, Azure Notebook, etc.)
  • Someone gave you an advice you liked? Test it - maybe the advice was actually bad.
  • Someone gave you an advice you think is bad? Test it before arguing - maybe it was good.
  • You posted a claim that something you did not test works? Be prepared to eat your hat.
Reply


Possibly Related Threads…
Thread Author Replies Views Last Post
  Split dict of lists into smaller dicts of lists. pcs3rd 3 2,377 Sep-19-2020, 09:12 AM
Last Post: ibreeden
  sort lists of lists with multiple criteria: similar values need to be treated equal stillsen 2 3,284 Mar-20-2019, 08:01 PM
Last Post: stillsen

Forum Jump:

User Panel Messages

Announcements
Announcement #1 8/1/2020
Announcement #2 8/2/2020
Announcement #3 8/6/2020