Search code examples
pythonlistnlptuples

Access n:th element of every list in list of lists


I have a problem in python and one step I need to do is to access the second element of every list in a list of lists. The list is:

[(0, 'Gallery', 'PROPN', 'nsubj'), (1, 'unveils', 'VERB', 'root'), (2, 'interactive', 'ADJ', 'amod')]

[(0, 'A', 'DET' 'det'), (1 'Christmas' , 'PROPN', 'compound'), (2, 'tree' ,'NOUN', 'nsubjpass')]

The list goes on like that with different sentences for each list.

What I am trying to do is access the third (index 2) element of every list of every tuple. So from the first list, I want to get:

  1. PROPN (from 'Gallery')
  2. VERB (from 'unveils')
  3. ADJ (from 'interactive')

And from the second list I want to get:

  1. DET (from 'A')
  2. PROPN (from 'Christmas')
  3. NOUN (from 'nsubjpass)

What I've tried to do is this:

for word in list:
      print(list[word[0]][2])

But that only outputs the second element from the first list. I tried creating another foor-loop but that didn't work, I suspect I did it wrong but I'm not sure how to solve it

Help would be appreciated

Thanks in advance!


Solution

  • when you are enumerating over the list in the for loop:

    for word in words:
        pass // do something
    

    You have already accessed the element in the list and stored it in word.

    As such, word[0] in your loop would be accessing the first element in your word tuple which is not what you'd like to do.

    Instead, you'd like to access word[2] in your tuple, so something like this should work:

    first_list = [(0, 'Gallery', 'PROPN', 'nsubj'), (1, 'unveils', 'VERB', 'root'), (2, 'interactive', 'ADJ', 'amod')]
    
    second_list = [(0, 'A', 'DET' 'det'), (1, 'Christmas' , 'PROPN', 'compound'), (2, 'tree' ,'NOUN', 'nsubjpass')]
    
    def print_word_pos(words):
        for word in words:
            print(word[2])
    
    print_word_pos(first_list)
    print_word_pos(second_list)
    

    Another thing is that you should not be naming your lists as list since list is a reserved python keyword and might (will) cause conflict later down the line.

    Now if the first two lists were combined, you'd want to loop over each list and then for each word in that list, print out the part of speech.

    def print_word_pos(list_of_words):
        for words in list_of_words:
            for word in words:
                print(word[2])