Python Forum
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: IndexError: list index out of range (/thread-32155.html)



IndexError: list index out of range - ramu4651 - Jan-24-2021

Hi Team,

I am facing below error while executing the code . Dont know where exactly the error exists . Could you please help me on this

#Reading Data from Files into Collections
orders_file = open('/content/sample_data/orders.txt')
orders_raw = orders_file.read()
# here orders_raw is read as String file
orders = orders_raw.splitlines()
# It will convert each row into string (orders) and put it in list
#len(orders)
#orders[0]
orders[0:10]
#for i in orders[0:10]: print(i)

def get_customer_orders(orders,customer_id):
    orders_filtered = []
    for i in orders:
        if int(i.split(',')[2])==customer_id:
            orders_filtered.append(i)
    return orders_filtered
Error Details

---------------------------------------------------------------------------
Error:
IndexError Traceback (most recent call last) <ipython-input-40-d6ac476436e2> in <module>() ----> 1 print(get_customer_orders(orders,11599)) <ipython-input-39-eacfbc89ef92> in get_customer_orders(orders, customer_id) 2 orders_filtered = [] 3 for i in orders: ----> 4 if int(i.split(',')[2])==customer_id: 5 print(i.split(',')[2]) 6 orders_filtered.append(i) IndexError: list index out of range
Data
----

Output:
['1,2013-07-25 00:00:00.0,11599,CLOSED', '2,2013-07-25 00:00:00.0,256,PENDING_PAYMENT', '3,2013-07-25 00:00:00.0,12111,COMPLETE', '4,2013-07-25 00:00:00.0,8827,CLOSED', '5,2013-07-25 00:00:00.0,11318,COMPLETE', '6,2013-07-25 00:00:00.0,7130,COMPLETE', '7,2013-07-25 00:00:00.0,4530,COMPLETE', '8,2013-07-25 00:00:00.0,2911,PROCESSING', '9,2013-07-25 00:00:00.0,5657,PENDING_PAYMENT', '10,2013-07-25 00:00:00.0,5648,PENDING_PAYMENT']



RE: IndexError: list index out of range - BashBedlam - Jan-24-2021

In my system, this code works as expected. Can you post all of the code that is creating the error?

orders_file = open('orders.txt')
orders_raw = orders_file.read()
orders_file.close ()
orders = orders_raw.splitlines()
 
def get_customer_orders(orders,customer_id):
	orders_filtered = []
	for i in orders:
		if int(i.split(',')[2])==customer_id:
			orders_filtered.append(i)
	return orders_filtered

print (get_customer_orders (orders, 256))
Output:
["'2,2013-07-25 00:00:00.0,256,PENDING_PAYMENT',"]



RE: IndexError: list index out of range - buran - Jan-24-2021

check your data. is it possible that you have blank/incomplete lines?
your code works for sample data