for value in my_list: print value
for value in my_list: print value, print # this starts a new line, when we're finished
column = 1 for value in my_list: print value, if column == 10: print # starts a new line column = 0 column += 1 if column < 10: # if last line had less than 10 values, print # finish it off
column = 1 for value in my_list: print value, if column % 10 == 0: print # starts a new line column += 1 if column % 10 != 0: # if last line had less than 10 values, print # finish it off
for index in range(len(my_list)): print value, if index % 10 == 0: print # starts a new line if len(my_list) % 10 != 0: print
total = 0 for value in my_list: total += valueBy the way,
total = sum(my_list)
does the same thing for you!
total = 0 for value in my_list: total += value average = total / len(my_list)
biggest = my_list[0] for value in my_list[1:] : if value > biggest: biggest = valueBy the way,
biggest = max(my_list)
does the same thing for you!
smallest = my_list[0] for value in my_list[1:] : if value < smallest: smallest = valueBy the way,
smallest = min(my_list)
does the same
thing for you!
all_even = True: for value in my_list: if value % 2 != 0: all_even = False break
has_string = False: for value in mylist: if type(value) == type(''): has_string = True break
has_odd = False for index in range(len(my_list)): value = my_list[index] if value % 2 == 1: has_odd = True odd_index = index breakNotice that this exits upon finding the first odd value. There may be other odd values in the list.
has_odd = False odd_total = 0 for value in my_list: if value % 2 == 1: has_odd = True odd_total += value
odd_count = 0 for value in my_list: if value % 2 == 1: odd_count += 1
biggest_odd = my_list[0]
, because the first
value may not be odd. In fact, there may not be any odd values!
So, we will initialize biggest_odd
the first
time we find an odd value. Hence we need a flag to know if it's
the first time:
has_odd = False first = True for value in my_list: if value % 2 == 1: if first: biggest_odd = value first = False elif value > biggest_odd: biggest_odd = value if has_odd: print 'Biggest odd value:', biggest_odd else: print 'No odd values'
is_sorted = True for index in range(1, len(my_list)): # index starts at second entry if my_list[index] < my_list[index - 1]: is_sorted = False break
previous_value = value
, to prepare for the next
time through the loop:
is_sorted = True previous_value = my_list[0] for value in my_list[1:] : if value < previous_value: is_sorted = False break previous_value = value
all_same = True first_value = my_list[0] for value in my_list[1:] : if value != first_value all_same = False break
is_palindromic = True for index in range(len(my_list)): if my_list[index] != my_list[-(index + 1)]: is_palindromic = False break