Python Forum
Preventing: IndexError: list index out of range - Printable Version

+- Python Forum (https://python-forum.io)
+-- Forum: Python Coding (https://python-forum.io/forum-7.html)
+--- Forum: General Coding Help (https://python-forum.io/forum-8.html)
+--- Thread: Preventing: IndexError: list index out of range (/thread-18845.html)



Preventing: IndexError: list index out of range - PappaBear - Jun-03-2019

I understand how to use a for loop with range(len(list)) to be able to cycle through and address each item in a list.
However (and in my case a directory listing), I'm trying to figure out how to provide (print in this case) the next 5 in the list. However when the list is down to the last 3 --and not 5, I get list-index-o-o-r; which makes sense, but i'm not sure how to approach this without a whole lot of "if/then/elif" etc.

So if I have 13 files, I want to print the first 5, ask a question (continue?) and present the next 5, etc, and then present onyly the last 3

..so when it's 13 items, I'll obviously get the l-i-o-o-r error;

Is there an "elegant" way, or a built in way to do this... or do I need to implement a modulus (%5) to see if there are additional files; and also validate i'm not at end of list, etc.

import os
temp_dir = os.listdir("c:\\temp")

'''
# This works no prob
for item in temp_dir:
	print (item)
	answer = input('Continue? y/n')
	if answer == 'n':
		break
'''
for by5 in range(0,len(temp_dir),5):
	print (temp_dir[by5])
	print (temp_dir[by5+1])
	print (temp_dir[by5+2])
	print (temp_dir[by5+3])
	print (temp_dir[by5+4])
Thanks, banging my head over the weekend but felt like there might be a "c'mon old man, use function widget to do that"

Pappa Bear

Well, it appears that yield may be what I was looking for... still not sure if this is the best method -- essentially breaks the list into n chunks, which are in a list... [ [1a 1b 1c 1d 1e] [2a 2b 2c 2d 2e] [3a 3b] ] giving me 3chunks of 5 (okay, 2 chunks of 5 and 1 chunk of remainder)

def into_chunks(list, size): 
    for counter in range(0, len(list), size):  
        yield list[counter:counter + size] 

chunk_size = 5
temp_dir = os.listdir("c:\\temp")
dir_list = list(into_chunks(temp_dir, chunk_size)) 

for group in dir_list:
	for file in group:
		print (file)
	print ("Continue? ")
Thoughts on this being the best method? Right now I'm simply printing continue...but will be implementing a crude menu system (select file by 'a/b/c/d/e/next')

Thanks,
Pappa Bear


RE: Preventing: IndexError: list index out of range - SheeppOSU - Jun-03-2019

Use a try and except
for by5 in range(0,len(temp_dir),5):
    try:
        print (temp_dir[by5])
        print (temp_dir[by5+1])
        print (temp_dir[by5+2])
        print (temp_dir[by5+3])
        print (temp_dir[by5+4])
    except:
        print('That\'s all')

So you try to print everything, except if you get an error it is probably the index error meaning you are done.