0

I'am working on a exercise and I can't see where I get it wrong. I'm trying to add the indexes of the sum of two numbers to a list, but instead of getting the indexes, I'm actually getting the numbers. Here is my code, and many thanks in advance for your precious help and time.

a_list = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]

target_list = []

counter = 0

for i in range(len(a_list)):
  for j in a_list:
      if i + j == 10:
          target_list.append((a_list.index(i), a_list.index(j)))
          counter += 1

print(target_list)

how can I do it with list comprehension. Thank you again and again.

4
  • 1
    What purpose does the counter variable serve? It is also not entirely clear what output you expect since the indeces are equal to the values in your example. Pls chose more general sample data and show the expected output. Commented Dec 20, 2020 at 11:08
  • 1
    Look up enumerate() Commented Dec 20, 2020 at 11:10
  • 1
    you have no problem in your specific case cuz item IS index, what are you expecting? Commented Dec 20, 2020 at 11:10
  • I got it guys. Thank you very much Commented Dec 21, 2020 at 14:44

2 Answers 2

1

You are getting the indexes, here is an example, if you change your list to:

a_list = [0, 10, 20, 30, 40, 50, 60, 70, 80, 90]

The output would be different:

[(0, 1)]
Sign up to request clarification or add additional context in comments.

Comments

0

what you did doesnt make any sense.. :

a_list = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]

target_list = []
for i in range(len(a_list)):
  for j in a_list:
      if i + j == 10:
          target_list.append((a_list.index(i), a_list.index(j)))
>>> target_list 
[(1, 9), (2, 8), (3, 7), (4, 6), (5, 5), (6, 4), (7, 3), (8, 2), (9, 1)]

which is equal to :

a_list = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]

target_list = []
for i in a_list:
  for j in a_list:
      if i + j == 10:
          target_list.append((a_list.index(i), a_list.index(j)))
>>> target_list 
[(1, 9), (2, 8), (3, 7), (4, 6), (5, 5), (6, 4), (7, 3), (8, 2), (9, 1)]

the point in python loops is that when you call for <item> in <Iterable>: it inserts the items to item and iterating each one by order, when you call range(len(list_a)) it generates a list from 0 to the length of a_list , that is eaqual to [0,1,2,3,4,5,6,7,8,9] and this is the same thing as you list...

you could also do the following:

target_list = [(i,j) for j in range(10) for i in range(10) if j+i ==10]
Target_list 
>>>
[(9, 1), (8, 2), (7, 3), (6, 4), (5, 5), (4, 6), (3, 7), (2, 8), (1, 9)]

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.