Reputation: 97
I have a list of floating point numbers that I need to iterate over and find the lowest out of the last 4 numbers
list = [1.1344, 1.254, 1.654, 1.2335, 1.43545]`
for i in list [-4]:
print i
but I keep getting:
TypeError: 'float' object is not iterable
Upvotes: 2
Views: 13066
Reputation: 253
when you reference a specific element in a list you specify his position, by index. positive index value means that count should start from left to right, negative number means that count should start from right to left.
a = [0.1, 1.1, 2.1, 3.1, 4.1]
b = a[-4]
print(b)
# this will print 1.1
so you refer to one element but not to a range of elements in original list.
To get a slice of a
you should use something like this
a = [0.1, 1.1, 2.1, 3.1, 4.1]
b = a[-4:]
print(b)
# this will print [1.1, 2.1, 3.1, 4.1]
so, to refer a range of elements you should indicate that range and it can be done in this way list[start_index:end_index]
(note semicolons)
Iterate through a list of integers, strings or a list of floats isn't something diferent. They are all handled in the same way, you just have a syntax error, that is. check for
line with the explanation in mind.
UPDATE:
you can use min
function to get minimum value from a list of elements without iterating through elements. it would be something like this min_value = min(list[-4:])
Upvotes: 4
Reputation: 2358
The first part of a slice is the beginning. If you don't supply a second part it just gets that element try the following:
for i in list [-4:]:
Upvotes: 0
Reputation: 245419
Right now, your code only fetches the fourth last item from the list.
If you want to fetch the last four elements from the array to iterate over, you need to change the code a hair:
for i in list[-4:]:
print i
Upvotes: 0