0

I want to use the array.index(x) function multiple times to find the element index in a small list and its place within a larger list. For example, I have...

a=1
b=2
c=1
d=2

small_list = [a, b, c]
full_list = [d, c, b, a]

x=small_list.index(c)
y=full_list.index(x)
z=full_list[y]

When running, I get...

x=0
y=0
z=2

But I want to get...

x=2
y=1
z=1

How do I change my code to do this? I can see that it is looking up the value of c when I run the code. How do I stop this happening?

EDIT: My own answer to my problem is below.

2
  • "When running, I get..." You do? I get ValueError: 0 is not in list. Is this your actual code? Commented Mar 21, 2014 at 13:34
  • I'm not sure how your example input is meant to lead to your example output. Certainly the first index of 1 in your small_list is not 2. Commented Mar 21, 2014 at 13:39

4 Answers 4

1

You're using a list, not an array. The list.index() method returns the index of the first value specified. So, when you ask for

small_list.index(c)

You're getting the index of c, which are the values 0 and 1, respectively.

http://docs.python.org/2/tutorial/datastructures.html#more-on-lists

Sign up to request clarification or add additional context in comments.

Comments

0

I t looks like it is returning the correct value! Your list [a,b,c] is [1,2,1]. So the index(c) (or index(1)) is returning the first instance of c, which is spot 0.

Comments

0

Ahh, I've found what I need to do: Lists aren't the right basis for what I want to do, I think I should use tuples. That way, if I define...

tuple1 = (a, b, c)
tuple2 = (d, c, b, a)

print(tuple1[c]) # =2
print(tuple2[c]) # =1

Which is what I want. Essentially, I wanted the code to find the position of the variable c, not the position of the value of c.

Thank you to all answerers.

Comments

0

Calling small_list.index(c) is equivalent to calling small_list.index(1). The interpreter evaluates the value of c which is 1.

index() returns the first occurrence position of the specified value and that is at position 0.

See: http://docs.python.org/2/tutorial/datastructures.html

Comments

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.