0

new to programming. I have an issue where I need to modify a loop that searches a list in order to use indexes and start at index 1.

# find the coldest day in a range of daily temps
## input: 7 days worth of temps
temps = [7, 4, 1, -9, 18, 32, 10]

## output: lowest temp among the list
coolest = temps[0]

for temperature in temps:
    if temperature < coolest:
        coolest = temperature
print (coolest)

I want to change this so that we start at index 1, since using the current implementation causes a redundant step on the first iteration.

Many thanks, Michael

vurmux
  • 9,420
  • 3
  • 25
  • 45
Hydra17
  • 103
  • 7

3 Answers3

3

Instead of manual iterating through the list, you can use built-in function min and string slicing:

temps = [7, 4, 1, -9, 18, 32, 10]
print(min(temps[1:]))

-9

vurmux
  • 9,420
  • 3
  • 25
  • 45
1

You can use slicing here.

for temperature in temps[1:]:
    if temperature < coolest:
        coolest = temperature
Paritosh Singh
  • 6,034
  • 2
  • 14
  • 33
0

A very short and preferable way to find the minimum temperature value in the list is using pythons min function

coolest = min(temps)

If you want to write a loop over a list with indices, you can do it like that (it is what people are used to from other languages like C, but not recommended in python unless you really need the index, which is not the case here):

coolest = temps[0]

for i in range(1,len(temps)):
    if temps[i] < coolest:
        coolest = temps[i]
print (coolest)

index i will start at 1 up to the length of the list temps.

I agree with Paritosh Singhs concerns in the comments and therefore want to point out the link there with further descriptions why it is bad practise to loop with indices in python.

Since you might see this very often, in my opinion it is good to know how it works when you also know why and when not to use it. I recommend to follow the link in the comment below.

lidrariel
  • 79
  • 6
  • Do not iterate using indexes if you don't need to. It is considered bad form in python. [further read](https://nedbatchelder.com/text/iter.html) – Paritosh Singh May 27 '19 at 12:48
  • I agree that one should not use indices if not needed. I would always go for the single line solution in this case. Just wanted to also answer the question how looping over a list with indices works in general. – lidrariel May 27 '19 at 12:56
  • I think for someone new to python, it is important not to show them "bad practices" before they realize there's any issues with such practices, unless you add warnings about why it's bad. And even then. Iterating over indexes when it's not necessary is a very common bad form. – Paritosh Singh May 27 '19 at 13:01