Home > database >  add list values to new lists, using for loop and conditional statment - python
add list values to new lists, using for loop and conditional statment - python

Time:12-09

Hello I have a list with temperature values:

temperatures=[-2,1,10.2,6,15,-6,20,13.5,0.9,-8.3]

and I want to create 2 list containing 1 the values above zero and the other the values below. It is an exercise and I have to use for loop and conditional statment.

I created two additional empty values and I try to use the conditional statment to select the two ranges of values to complete the task, but Iàm not reaching the objective. Could you help?

this is the code I tried: 


```
temperatures=[-2,1,10.2,6,15,-6,20,13.5,0.9,-8.3]
temp_below_zero=[]
temp_above_zero=[]
for i in range(len(temperatures):
        if i  < 0 :
            temp_below_zero.append(i)
        elif i > 0 :
        temp_above_zero.append(i)
print(temp_below_zero,temp_above_zero)
```
`

```

CodePudding user response:

You enumerated the value 'i', but didn't use it as an indexer for the list. You could either do this, or just iterate over each element in the list by itself:

temperatures=[-2,1,10.2,6,15,-6,20,13.5,0.9,-8.3]
temp_below_zero=[]
temp_above_zero=[]
for i in temperatures:
        if i  < 0 :
            temp_below_zero.append(i)
        elif i > 0 :
            temp_above_zero.append(i)
print(temp_below_zero,temp_above_zero)

or using indexing (which I think you initially wanted to do):

temperatures=[-2,1,10.2,6,15,-6,20,13.5,0.9,-8.3]
temp_below_zero=[]
temp_above_zero=[]
for i in range(len(temperatures)):
        if temperatures[i] < 0 :
            temp_below_zero.append(temperatures[i])
        elif temperatures[i] > 0 :
            temp_above_zero.append(temperatures[i])
print(temp_below_zero,temp_above_zero)

CodePudding user response:

This approach is very close and you are definitely on the right track. Take a look at your for loop.

 for i in range(len(temperatures):

The loop, in this case, will run from values 0 to 10 (not including 10) stored as i. If instead, you want i to store each of the values in the list, rewrite your loop like this:

 for i in temperatures:

This modification makes it so that i contains a value in the list through each iteration, instead of the indices of the list. I hope this is helpful!

  • Related