i'm trying to create a simple minimum function by comparing items in a list to each other.

list1 = [4,20,2,19,3254,234,21,03]

for i in list1:

   if list[0] < list[0+i]:

       print i

basically my thought process in pseudocode is

for all items in the list
if item n is less than item n+1
return item n

but i'm not sure how to loop the +1 after every n

so i tried to do it with the i in the for loop

any simple suggestions? i don't want to make this more complicated than it should be

Dani AI

Generated

The root cause here is mixing up values and indexes. Iterating with for x in some_list gives values; using range() gives indexes. If you need to compare an element with the next one, iterate indexes and stop before the last index. If you only want the smallest value, keep a running minimum and compare each subsequent value to it. was on the right track with a low variable, and correctly spotted the confusing i vs 1 issue that tripped up .

A simple, clear implementation that avoids index math is to walk the sequence from the second element and update a running minimum:

def minimum(seq):
    if not seq:
        raise ValueError("minimum() arg is empty")
    smallest = seq[0]
    for item in seq[1:]:
        if item < smallest:
            smallest = item
    return smallest

# example
print(minimum([7, 1, 9, -3, 4]))  # prints -3

Practical tips:

  • Handle empty input explicitly (raise an exception or return None).
  • Avoid ambiguous single-letter names (l, i, o) — use index, item, or smallest.
  • If you must compare neighbors, use for i in range(len(seq)-1) to prevent an index-out-of-range error.
  • Watch numeric literals: 03 is invalid syntax in Python 3 (in Python 2 it would be octal); use 3 instead.
  • For production, prefer Python’s built-in min() (O(n) time) unless implementing the function is the exercise goal.

Recommended Answers

All 5 Replies

You want to stop at the next to last item in the list, so "+1" will be the last item. Also, do not use "i", "l", or "o" as single letter variable names. They look too much like numbers.

list1 = [4,20,2,19,3254,234,21,03]

stop = len(list1) - 1
low = list1[0]
for x in range(0, stop):
   if list1[x] < list1[x+i]:
       print x, list1[x], list1[x+1]
   if list1[x+1] < low:
      low = list1[x+1]
print "lowest =", low

Thanks. That helps. In your program, i was not defined so i just set it equal to 0 before the loop.

Except I don't think he meant i there, but rather 1 (the number one). I can never be sure though.

sorry. set i = 1

Yes that should have been one to get the next value. A good example of why we don't use "i".

commented: good example +12
Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.