Question: I have the following homework assignment:

> 
> Add a new method `retrieveAt` for the class `IntSLList` that takes an integer index position as a parameter.
> 
> 
> The method returns the info inside the node at the index position. The index of the first node is 0. If the list is empty or the index is invalid, then display an error message.
> 
> 
> 

I have implemented a solution using the following code:

```java
public int retrieveAt(int pos){
    IntSLLNode tmp;
    int count = 0;
    int c;
    for(tmp = head; tmp != null; tmp = tmp.next){
        count++;
    }
    if(isEmpty()|| count<pos){
        return 0; 
    } else {
        IntSLLNode tmp1 = head;
        for(int i = 1; i < pos; i++){
            if(tmp1.next == null)
                return 0;
            tmp1 = tmp1.next;
        }
        return tmp1.info;
    }
}

```

It appears to traverse the list properly, but it does not retrieve the correct element.

An example case where this does not appear to give the correct output:

```java
IntSLList myn = new IntSLList();

myn.addToHead(10);
myn.addToHead(20);
myn.addToHead(30);
myn.addToHead(40);
myn.addToTail(60);
myn.printAll();

int x = myn.retrieveAt(4);
if(x == 0)
    System.out.println("NOT VALID ");
else
    System.out.println("elm : " + x);

```

The output is:

```
40 
30 
20 
10 
60 
elm : 10

```

Answer: 
In python 3.6.7, the comments on the get\_all() method explicity state that the values are returned in the same order as they are in the message, so `messageInstance.get_all('Received')` should work fine.

```
def get_all(self, name, failobj=None):
    """Return a list of all the values for the named field.

    These will be sorted in the order they appeared in the original
    message, and may contain duplicates.  Any fields deleted and
    re-inserted are always appended to the header list.

    If no such fields exist, failobj is returned (defaults to None).
    """

```
The `email.parser` class `HeaderParser` implements a dictionary-like interface, but actually seems to return the headers in the order you expect.

```
from email.parser import HeaderParser

headers = HeaderParser().parse(open_filehandle, headersonly=True)
for key, value in headers.items():
    if key == 'Received':
        ... do things with the value

```

The [`parse` method](https://docs.python.org/2/library/email.parser.html#email.parser.Parser.parse) has a sister [`parsestr` method](https://docs.python.org/2/library/email.parser.html#email.parser.Parser.parsestr) which accepts a byte string instead of a file-like object.

If by "final" you mean the "newest", that will be the first one which matches the `if` so you can simply `break` after reading it. If by "final" you mean something else, you can implement that inside the `if` in whatever way you see fit.

This is adapted from [this answer to a related question](https://stackoverflow.com/questions/8424317/extract-just-email-headers-in-python).