0

I'm learning Liste / Matrice in Python and I would like to make some addition in Liste. Let me explain, in the exemple, in the Table "exam_liste" the second position (1 in python) I want to add +2 and refresh the table, I don't want to insert anything, I want to make an addition directly in the Liste and in my exemple it doesn't working.

Anyone can explain me this ?

 ote = 1

 exam_liste = [None] * 5
 print(exam_liste)


 exam_liste.insert(1,note)
 print(exam_liste)

 exam_liste.insert(1,exam_liste[1]+2)
 print(exam_liste)

 >>> [None, None, None, None, None]
 >>> [None, 1, None, None, None, None]
 >>> [None, 3, 1, None, None, None, None]

I was waiting like : [None, 3, None, None, None, None, None]

1
  • You want to map things: map(lambda x: x if x is None else x + 2, list). Or just use list[index] += value Commented Dec 7, 2018 at 16:21

2 Answers 2

1

If you want to add to an integer in the list, you need to access the item and add to it, not insert another item into the list:

exam_liste[1] = exam_list[1] + 2

By using insert, you're adding an entirely new element to the list. If you want to modify an item from the list, you have to grab it with its index. But obviously you will have to insert an integer into the list before you can add to that integer. So after your list is created:

exam_liste.insert(1,note)
exam_liste[1] = exam_list[1] + 2
Sign up to request clarification or add additional context in comments.

1 Comment

Perhaps I wasn't clear, but I was assuming he still would have inserted a number into the first position before trying to add to it. Seems logical
0

This is the definition of insert:

list.insert(index, elem)

Which it means, insert the element at the given index, shifting elements to the right. So when you write exam_liste.insert(1,exam_liste[1]+2) it will add exam_liste[1]+2 which is 3 to the second element of previous list which was [None, 1, None, None, None, None]

Rather than using exam_liste.insert(1,exam_liste[1]+2), use the following line:

exam_liste[1] +=2

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.