Jergh
Jergh

Reputation: 13

Basic list iteration in python

Very new to python. I am trying to iterate over a list of floating points and append elements to a new list based on a condition. Everytime I populate the list I get double the output, for example a list with three floating points gives me an output of six elements in the new list.

tempretures = [39.3, 38.2, 38.1]

new_list = []
i=0
while i <len(tempretures):
    for tempreture in range(len(tempretures)):
        if tempreture < 38.3:
            new_list = new_list + ['L']
        elif tempreture > 39.2:
            new_list = new_list + ['H']
        else: tempreture (38.3>=39.2)
        new_list = new_list + ['N']
        i=i+1

print (new_list)
print (i)
['L', 'N', 'L', 'N', 'L', 'N']
3

Upvotes: 1

Views: 105

Answers (4)

Mahamudul Hasan
Mahamudul Hasan

Reputation: 2823

Hope it will solve your issue:

tempretures = [39.3, 38.2, 38.1]
new_list = []
for temperature in tempretures:
    if temperature > 39.2:
        new_list.append('H')
    elif temperature>=38.3 and temperature<39.2:
        new_list.append('N')
    else:
        new_list.append('L')

print (new_list)

sample output: ['H', 'L', 'L']

Upvotes: 0

Josh Ackland
Josh Ackland

Reputation: 673

The cause of this is at the else: statement at the bottom, you haven't indented the line new_list = new_list + ['N'] so it is being ran no matter the result.

There are also a few other improvements which I've made and added comments explaining what it's doing

Change your code to this:

temperatures = [39.3, 38.2, 38.1]

new_list = []

for temperature in temperatures: #goes through all the values in "temperatures" and assigns it to the variable "temperature"
    if temperature < 38.3: #if temperature is less than 38.3
        new_list.append('L') #append (add) 'L' to the list
    elif temperature > 39.2: #if temperature is greater than 39.2
        new_list.append('H') #append 'H' to the list
    else: #else temperature is greater than or equal to 38.3 or less than or equal to 39.2
        new_list.append('N') #append 'N' to the list

Upvotes: 2

Chris
Chris

Reputation: 36536

It looks like you're looking for something like the below list comprehension, which should be a go to when you have a pattern of building a new list based on the values in an existing list.

new_list = ['L' if t < 38.3 else 'H' if t > 39.2 else 'N' for t in temperatures]

Upvotes: 2

Gab
Gab

Reputation: 3520

The issue is with the indentation of the line new_list = new_list + ['N']. Because it is under-indented, it runs for every instance.

If I can suggest an easier syntax:

temperatures = [39.3, 38.2, 38.1]

new_list = []
for temperature in temperatures:
    if temperature < 38.3:
        new_list.append('L')
    elif temperature > 39.2:
        new_list.append('H')
    else:
        new_list.append('N')

print(new_list)
print(len(new_list))

->

['H', 'L', 'L']
3

Upvotes: 1

Related Questions