Beginner here (meaning I probably did something silly):
I am trying to target indexed elements that have [A], in them. Entries for 'scarcity' and 'sweet' are both shown.

I am running into trouble when index item[2] is empty. I get the following message:

['scarcity', 'scarce', '[A],', 'ity', '[N|A]', '[N]']
scarcity	  scarce [A], ity [N|A] [N]
scarcity
[A],
['sweet', ',']
sweet	,
Traceback (most recent call last):
  File "final3.py", line 69, in <module>
    dict_pos = item[2]
IndexError: list index out of range

This is what the code is:

for line in dictionary:

        line = line.replace('(', ' ').replace(')', ' ')
        item = line.split()

        print item
        print line

        dict_word = item[0]
        dict_base = item[1]
        dict_pos = item[2]

        print dict_word

        if not dict_pos:
                print "[X],"
        else:
                print dict_pos

Any thoughts?

Thank you!

The dictionary is undefined.

Here in DaniWeb you must but [CODE] and same with / before CODE as tags not simple square brackets.

Like this:

['scarcity', 'scarce', '[A],', 'ity', '[N|A]', '[N]']
scarcity      scarce [A], ity [N|A] [N]
scarcity
[A],
['sweet', ',']
sweet   ,
Traceback (most recent call last):
  File "final3.py", line 69, in <module>
    dict_pos = item[2]
IndexError: list index out of range

This is what the code is:

for line in dictionary:

    line = line.replace('(', ' ').replace(')', ' ')
    item = line.split()

    print item
    print line

    dict_word = item[0]
    dict_base = item[1]
    dict_pos = item[2]

    print dict_word

    if not dict_pos:
            print "[X],"
    else:
            print dict_pos      

Thank you for the response, but I don't think this is the problem....

My dictionary is defined earlier in the program (lines 1-6 of run show this). So why will it not print line 17

[print "[X]," ]

??? I think the problem lies somewhere in code lines 16-17 because when I take the 'sweet' entry out of the dictionary, it runs fine.

In other words, how do you get the program to ignore a non-existent index? I have gone through as many code boards as I can find, and I cannot find the answer to this...

Thank you for your patience...

Can you give us an example what object dictionary looks like?

dictionary = ['animosity        (animosity)[N]',
        'car    (car)[N]',
        'ess    (ess)[N]',
        'happiness      ((happy)[A],(ness)[N|A])[N]',
        'mediocrity     ((mediocre)[A],(ity)[N|A])[N]',
        'scarcity       ((scarce)[A],(ity)[N|A])[N]',
        'sweet  ,',
        'thoughtfulness ((thoughtful)[A],(ness)[N|A])[N]']
Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.