473,405 Members | 2,261 Online
Bytes | Software Development & Data Engineering Community
Post Job

Home Posts Topics Members FAQ

Join Bytes to post your question to a community of 473,405 software developers and data experts.

IndexError: list index out of range

My code
Expand|Select|Wrap|Line Numbers
  1. s=['aaaa','cccccccc','dddd','ssss','xxxxx','aaaa','ssx','ssx','cc','cc']
  2.  
  3. for k in range(len(s)):
  4.     st=s.count(s[k])
  5.     if st>=2:
  6.        print s.pop(s.index(s[k]))
  7.  
  8. Traceback (most recent call last):
  9.   File "C:/Python30/test.py", line 4, in <module>
  10.     st=s.count(s[k])
  11. IndexError: list index out of range
  12.  
how can I fix the error
IndexError: list index out of range
Oct 5 '07 #1
7 10751
bartonc
6,596 Expert 4TB
My code
Expand|Select|Wrap|Line Numbers
  1. s=['aaaa','cccccccc','dddd','ssss','xxxxx','aaaa','ssx','ssx','cc','cc']
  2.  
  3. for k in range(len(s)):
  4.     st=s.count(s[k])
  5.     if st>=2:
  6.        print s.pop(s.index(s[k]))
  7.  
  8. Traceback (most recent call last):
  9.   File "C:/Python30/test.py", line 4, in <module>
  10.     st=s.count(s[k])
  11. IndexError: list index out of range
  12.  
how can I fix the error
IndexError: list index out of range
That would be because of the pop(). When you shorten the list that you are indexing on you cause the error.

By using a slice for beginning to end, you work on a copy. I threw in some other options which avoid the index all together:
Expand|Select|Wrap|Line Numbers
  1. >>> s=['aaaa','cccccccc','dddd','ssss','xxxxx','aaaa','ss  x','ssx','cc','cc']
  2. >>> for item in s[:]:
  3. ...     n = s.count(item)
  4. ...     if n >= 2:
  5. ...         print item
  6. ...         s.remove(item)
  7. ...         
  8. aaaa
  9. cc
  10. >>> s
  11. ['cccccccc', 'dddd', 'ssss', 'xxxxx', 'aaaa', 'ss  x', 'ssx', 'cc']
  12. >>> 
Oct 5 '07 #2
Motoma
3,237 Expert 2GB
That would be because of the pop(). When you shorten the list that you are indexing on you cause the error.

By using a slice for beginning to end, you work on a copy. I threw in some other options which avoid the index all together:
Expand|Select|Wrap|Line Numbers
  1. >>> s=['aaaa','cccccccc','dddd','ssss','xxxxx','aaaa','ss  x','ssx','cc','cc']
  2. >>> for item in s[:]:
  3. ...     n = s.count(item)
  4. ...     if n >= 2:
  5. ...         print item
  6. ...         s.remove(item)
  7. ...         
  8. aaaa
  9. cc
  10. >>> s
  11. ['cccccccc', 'dddd', 'ssss', 'xxxxx', 'aaaa', 'ss  x', 'ssx', 'cc']
  12. >>> 
Just as a note:

Expand|Select|Wrap|Line Numbers
  1. for item in s[:]:
  2.  
is exactly the same as

Expand|Select|Wrap|Line Numbers
  1. for item in s:
  2.  
The only reason I mention this is that when learning Python, I often stumbled when I would encounter the whole array-subarray-step-bracket-thingies.
Oct 5 '07 #3
My code
Expand|Select|Wrap|Line Numbers
  1. s=['aaaa','cccccccc','dddd','ssss','xxxxx','aaaa','ssx','ssx','cc','cc']
  2.  
  3. for k in range(len(s)):
  4.     st=s.count(s[k])
  5.     if st>=2:
  6.        print s.pop(s.index(s[k]))
  7.  
  8. Traceback (most recent call last):
  9.   File "C:/Python30/test.py", line 4, in <module>
  10.     st=s.count(s[k])
  11. IndexError: list index out of range
  12.  
how can I fix the error
IndexError: list index out of range
Here is a way to get rid of duplicate items in a list that probably isn't good form, but I thought it was interesting. I put everything in a dictionary, which can't have duplicate keys, and then retrieved the list of keys.
Expand|Select|Wrap|Line Numbers
  1. >>> s=['aaaa','cccccccc','dddd','ssss','xxxxx','aaaa','ssx','ssx','cc','cc']
  2. >>> d=dict([(s[i], i) for i in range(len(s))])
  3. >>> s=d.keys()
  4. >>> print s
  5. ['cccccccc', 'ssss', 'ssx', 'cc', 'aaaa', 'dddd', 'xxxxx']
If you were using an ordered list this way wont work because the dictionary keys are in an unordered list.
Oct 5 '07 #4
Just as a note:

Expand|Select|Wrap|Line Numbers
  1. for item in s[:]:
  2.  
is exactly the same as

Expand|Select|Wrap|Line Numbers
  1. for item in s:
  2.  
The only reason I mention this is that when learning Python, I often stumbled when I would encounter the whole array-subarray-step-bracket-thingies.
It's actually different (and very useful) because "s[:]" creates a whole new list (a deep copy) to iterate through, instead of iterating over "s" itself. That way the loop can modify "s" without throwing an error.
Oct 5 '07 #5
Motoma
3,237 Expert 2GB
It's actually different (and very useful) because "s[:]" creates a whole new list (a deep copy) to iterate through, instead of iterating over "s" itself. That way the loop can modify "s" without throwing an error.
Oh man...Owned.

You learn something new every day. Thanks for the lesson KaesarRex!
Oct 5 '07 #6
bartonc
6,596 Expert 4TB
It's actually different (and very useful) because "s[:]" creates a whole new list (a deep copy) to iterate through, instead of iterating over "s" itself. That way the loop can modify "s" without throwing an error.
Actually, Motoma has a point. When working with arrays, the elements are passed by reference (even in a slice). Lists and arrays are not interchangeable that way!
Oct 5 '07 #7
Actually, Motoma has a point. When working with arrays, the elements are passed by reference (even in a slice). Lists and arrays are not interchangeable that way!
Looks like I've learned something too. Thanks for the clarification.
Oct 5 '07 #8

Sign in to post your reply or Sign up for a free account.

Similar topics

6
by: Ishwor | last post by:
i am trying to remove an item 'e' from the list l but i keep getting IndexError. I know the size of the list l is changing in the for loop & its sort of trivial task but i found no other way than...
7
by: Derek Schuff | last post by:
I'm sorry if this is a FAQ or on an easily-accesible "RTFM" style page, but i couldnt find it. I have some code like this: for line in f: toks = line.split() try: if int(toks,16) ==...
23
by: comp.lang.tcl | last post by:
I have a TCL proc that needs to convert what might be a list into a string to read consider this: ]; # OUTPUTS Hello World which is fine for PHP ]; # OUTPUT {{-Hello}} World, which PHP...
0
by: cindy | last post by:
I have a dynamic datagrid. I have custom classes for the controls public class CreateEditItemTemplateDDL : ITemplate { DataTable dtBind; string strddlName; string strSelectedID; string...
35
by: erikwickstrom | last post by:
Hi all, I'm sorry about the newbie question, but I've been searching all afternoon and can't find the answer! I'm trying to get this bit of code to work without triggering the IndexError. ...
4
by: BurnTard | last post by:
Okay, so I know what an IndexError is and all, but that doesn't help me understand why on earth I'm getting this one. I'm writing a program that's supposed skim through directories, dump all files...
33
by: John Salerno | last post by:
Is it possible to write a list comprehension for this so as to produce a list of two-item tuples? base_scores = range(8, 19) score_costs = print zip(base_scores, score_costs) I can't think...
0
by: emmanuelkatto | last post by:
Hi All, I am Emmanuel katto from Uganda. I want to ask what challenges you've faced while migrating a website to cloud. Please let me know. Thanks! Emmanuel
1
by: nemocccc | last post by:
hello, everyone, I want to develop a software for my android phone for daily needs, any suggestions?
1
by: Sonnysonu | last post by:
This is the data of csv file 1 2 3 1 2 3 1 2 3 1 2 3 2 3 2 3 3 the lengths should be different i have to store the data by column-wise with in the specific length. suppose the i have to...
0
by: Hystou | last post by:
There are some requirements for setting up RAID: 1. The motherboard and BIOS support RAID configuration. 2. The motherboard has 2 or more available SATA protocol SSD/HDD slots (including MSATA, M.2...
0
marktang
by: marktang | last post by:
ONU (Optical Network Unit) is one of the key components for providing high-speed Internet services. Its primary function is to act as an endpoint device located at the user's premises. However,...
0
by: Hystou | last post by:
Most computers default to English, but sometimes we require a different language, especially when relocating. Forgot to request a specific language before your computer shipped? No problem! You can...
0
by: Hystou | last post by:
Overview: Windows 11 and 10 have less user interface control over operating system update behaviour than previous versions of Windows. In Windows 11 and 10, there is no way to turn off the Windows...
0
agi2029
by: agi2029 | last post by:
Let's talk about the concept of autonomous AI software engineers and no-code agents. These AIs are designed to manage the entire lifecycle of a software development project—planning, coding, testing,...
0
isladogs
by: isladogs | last post by:
The next Access Europe User Group meeting will be on Wednesday 1 May 2024 starting at 18:00 UK time (6PM UTC+1) and finishing by 19:30 (7.30PM). In this session, we are pleased to welcome a new...

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.