2

So i have a list of heights:

heights = [1, 2, 3, 5, 7, 8, 8, 13]

And im using this function to store each height integer value and its index in the list in a class i called Node.

def initializeNodes(heights):
    ans = []
    for height in heights:
        ans.append(Node(heights.index(height), height))
    return ans

But my problem is, because their are two 8's in the list, its giving them both the same first 8 position of 5 in the list:

0 1
1 2
2 3
3 5
4 7
5 8
5 8
7 13

How can i go around this? Thanks!

3 Answers 3

6

Use enumerate() to generate an index:

def initializeNodes(heights):
    ans = []
    for i, height in enumerate(heights):
        ans.append(Node(i, height))
    return ans

You can collapse the four lines into 1 using a list comprehension:

def initializeNodes(heights):
    return [Node(i, height) for i, height in enumerate(heights)]
Sign up to request clarification or add additional context in comments.

1 Comment

This is perfect and surprisingly a lot simpler than i thought! lol haven't used python in a while and forgot how to use enumerate, silly me
1

The problem with list.index is that it'll only return the index of first occurrence of the item.

>>> heights = [1, 2, 2, 3, 5, 5, 7, 8, 8, 13]
>>> heights.index(2)
1
>>> heights.index(5)
4
>>> heights.index(8)
7

help on list.index:

L.index(value, [start, [stop]]) -> integer -- return first index of value.

You can do provide a different start value to list.index than 0, to get the index of repeated items:

>>> heights.index(5,heights.index(5)+1) #returns the index of second 5
5

But that is very cumbersome, a better solution as @MartijnPieters already mentioned is enumerate

Comments

0

The problem is that you're generating the index from the values, why not do it the other way around?

heights = [1, 2, 3, 5, 7, 8, 8, 13]

def initializeNodes(heights):
    ans = []
    for index in range(len(heights)):
        ans.append(Node(index, heights[index]))
    return ans

This creates a list from 0 to the length of heights, and then will append the index then the height at this index.

1 Comment

The enumerate way suggested by @Martijn Pieters is better though, mind.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.