Reputation: 191
I am trying to print the three middle indexes of any list in Python, but am having trouble figuring it out. I know how to find the three middle indexes on their own, but I can't seem to print all three in a list. Here's what I have so far.
print("Three items from the middle of the list are:")
middle = (int(len(numbers))/2)
middle_two = (int(len(numbers))/2) - 1
middle_three = (int(len(numbers))/2) + 1
print(list(middle + middle_two + middle_three))
Whenever I try to put list()
around any of the integers or concatenate them, I get an error: "'float' object is not interable'. I know what that means in practice, but I am stuck on how to turn all three middle indexes into a list.
Upvotes: 1
Views: 805
Reputation: 2776
There is a much simpler method than calculating these individually. You can simply find the middle of the list with len(numbers)//2
. We do the //2
to force integer division, which will return an int
. This is critical because the float that comes out of 3/2
, which is 1.5
, is not a valid list index. This makes sense, as there wouldn't be a 'one-and-a-half-th' item in a list.
On the other hand, 3//2
will return 1
, which is a valid index (remember, integer division)
Putting all these together in a function, we get this:
def middle_three(items:list):
assert len(items) >= 3, "middle_three needs at least 3 items in the input!"
middle = len(items)//2 # find the index of the middle of the list, rounded down for even lists
return items[middle-1:middle+2] # +2 because we want +1 from the middle, +1 more because of indexing syntax
We can try this out on some sample lists:
for i in range(3, 20):
print(i, ':', middle_three([*range(i)]))
3 : [0, 1, 2] 4 : [1, 2, 3] 5 : [1, 2, 3] 6 : [2, 3, 4] 7 : [2, 3, 4] 8 : [3, 4, 5] 9 : [3, 4, 5] 10 : [4, 5, 6] 11 : [4, 5, 6] 12 : [5, 6, 7] 13 : [5, 6, 7] 14 : [6, 7, 8] 15 : [6, 7, 8] 16 : [7, 8, 9] 17 : [7, 8, 9] 18 : [8, 9, 10] 19 : [8, 9, 10]
Upvotes: 1
Reputation: 4537
In you last line you are adding your indices a+b+c
and get a number, than you want to convert this number
to a list
, which results in an error:
list(9.0) # TypeError: 'float' object is not iterable
list(9) # TypeError: 'int' object is not iterable
You need to combine the indices to a list:
with [a, b, c]
:
import numpy as np
numbers = np.arange(10, 20)
print("Three items from the middle of the list are:")
middle = len(numbers) // 2 # ensure that your indices are integers
middle_two = middle - 1
middle_three = middle + 1
middle_list = [middle, middle_two, middle_three]
# ^ ^ ^ ^
print(middle_list) # [5, 4, 6]
print(numbers[middle_list]) # [15 14 16]
Upvotes: 0