Add to integers in list

I have a list of integers, and I was wondering if it is possible to add separate integers to them.

+4
source share
5 answers

Here is an example where things to add come from a dictionary

>>> L = [0, 0, 0, 0] >>> things_to_add = ({'idx':1, 'amount': 1}, {'idx': 2, 'amount': 1}) >>> for item in things_to_add: ... L[item['idx']] += item['amount'] ... >>> L [0, 1, 1, 0] 

Here is an example of adding items from another list

 >>> L = [0, 0, 0, 0] >>> things_to_add = [0, 1, 1, 0] >>> for idx, amount in enumerate(things_to_add): ... L[idx] += amount ... >>> L [0, 1, 1, 0] 

You can also achieve the above with list comprehension and zip

 L[:] = [sum(i) for i in zip(L, things_to_add)] 

Here is an example of adding from the list of tuples

 >>> things_to_add = [(1, 1), (2, 1)] >>> for idx, amount in things_to_add: ... L[idx] += amount ... >>> L [0, 1, 1, 0] 
+7
source

You can add to the end of the list:

 foo = [1,2,3,4,5] foo.append( 4 ) foo.append( [8,7] ) print(foo) #[1, 2, 3, 4, 5, 4, [8, 7]] 

You can edit the items in the list as follows:

 foo = [1,2,3,4,5] foo[3] = foo[3] + 4 print(foo) #[1,2,3,8,5] 

Insert integers in the middle of the list:

 x = [2,5,10] x.insert(2, 77) print(x) #[2, 5, 77, 10] 
+16
source
 fooList = [1,3,348,2] fooList.append(3) fooList.append(2734) print(fooList) # [1,3,348,2,3,2734] 
+3
source

Yes, it is possible, since lists are mutable.

Take a look at the built-in enumerate() function to get an idea of โ€‹โ€‹how to iterate over a list and find each record index (which you can then use to assign to a specific list item).

0
source

If you try to add a number, for example, say listName.append(4) , this will finally add 4 . But if you try to take an <int> , then add it like, num = 4 followed by listName.append(num) , this will give you an error like 'num' is of <int> type and listName is of type <list> . Therefore, before adding it, type int(num) .

0
source

Source: https://habr.com/ru/post/1334844/


All Articles