Python summing values in list if it exists in another list

list comprehension || python
write a python program to find the list in a list of lists whose sum of elements is the highest.
python sum list of lists
how to add corresponding elements of two lists in python
python list
python sum two lists
sum of nested list python
sum of sublist python

I have a list and a set:

a_list = [['1', 2], ['2', 1], ['1', 1]]

b_list = {'1', '2'}

I'm looking to correspond the items in b_list and sum their values from a_list so that the output is:

[['1', 3], ['2', 1]]

What I've tried...

sum = 0

for i in a_list:
        for j in b_list:
            if i[0] in j:
                sum += i[1]
        print(j, sum)

But this is giving giving me an incorrect output.

You are on the right track! All you have to do is flip the order of your loops. For every value in b_list, you want to sum up all matching values in a_list, so b_list should be the external loop and a_list the internal. Also note your sum variable should be inside the first loop as it is different for every value in b_list.

If you make this change your code works as expected:

a_list = [['1', 2], ['2', 1], ['1', 1]]

b_list = {'1', '2'}

for j in b_list:
    sum = 0
    for i in a_list:
        if i[0] == j:
            sum += i[1]
    print(j, sum)

will give your desired output:

('1', 3)
('2', 1)

EDIT: the above solution is a minimal fix to the code posted in the question, however there are more efficient solutions:

Similar to wim's answer, you could use a defaultdictionary, which in this case would be (slightly) more efficient than using the built-in dict class:

from collections import defaultdict
#
a_list = [['1', 2], ['2', 1], ['1', 1]]
b_list = {'1', '2'}

dict = defaultdict(int)

for key, val in a_list:
    if key in b_list:
        dict[key] += val

print([[key, dict[key]] for key in b_list])

** credit to coldspeed for the idea for this second solution.

Python, It contains well written, well thought and well explained computer science and programming The list is an important container and used almost in every code of day-day programming as Given a list of lists, the program to suppose to return the sum as the final list. first_page Python | Ways to sort a zipped list by values. In this sample program, you will learn to check if a Python list contains all the elements of another list and show the result using the print() function. To understand this demo program, you should have the basic Python programming knowledge.

Accumulate numbers using a dict, and then gather the results using a list comprehension:

>>> d = dict.fromkeys(b_list, 0)
>>> for k, n in a_list: 
...     if k in d: 
...         d[k] += n 
...
>>> [[k, n] for k, n in d.items()]
[['1', 3], ['2', 1]]

Python, Python | Check if a list is contained in another list · Python - Sum of different length Lists of list · Python | Split list into lists by particular value · Python | Product of kth  Python “in operator” is the most convenient way to check if an item exists on the list or not. This approach returns True if an item exists in the list and False if an item does not exist in the list. The list need not be sorted to practice this approach of checking. Check if the item exists in the list using Python in Operator

Use a dict for grouping:

d = {}
for k, v in a_list:
    d[k] = d.get(k, 0) + v
print([[k, d[k]] for k in b_list])

prints:

[['2', 1], ['1', 3]]

Bioinformatics Algorithms: Design and Implementation in Python, Design and Implementation in Python Miguel Rocha, Pedro G. Ferreira. g. Implement a method to validate if the sequence is valid (i.e. if it only contains the list resulting from summing the elements of the list with the ones of another list with  Check if element exists in list using python “in” Operator. Condition to check if element is in List : elem in LIST It will return True, if element exists in list else return false. For example check if ‘at’ exists in list i.e.

This returns sums only for items defined in find.

items = [['1', 2], ['2', 1], ['1', 1], ['3',1]]
find = {'1', '2'}
results = {}

for item in items:
    key = item[0]
    value = item[1]
    if key in find:
        results[key] = results.get(key,0) + value

[[key, value] for key, value in results.items()] 

Outputs [['2', 1], ['1', 3]]

How to Sum Elements of Two Lists in Python, Welcome back to another edition of the How to Python series. This time I want 1) How to Check if a File Exists in Python 2) How to Check if a List is Empty in Python 3 . This time I want to sum elements of two lists in Python. Python all () function checks if all Elements of given Iterable is True. So, convert the list2 to Iterable and for each element in Iterable i.e. list2 check if element exists in list1. Check if list1 contains any elements of list2 using any ()

In [1]: a_list = [['1', 2], ['2', 1], ['1', 1]]
   ...:
   ...: b_list = {'1', '2'}

In [2]: out = [[i, sum(j[1] for j in a_list if j[0] == i)] for i in b_list]

In [3]: out
Out[3]: [['1', 3], ['2', 1]]

You can use sum of list or you can directly call sum. Here is a time performance of both approach:

In [6]: %timeit [[i, sum(j[1] for j in a_list if j[0] == i)] for i in b_list]
1.31 µs ± 2.52 ns per loop (mean ± std. dev. of 7 runs, 1000000 loops each)

In [7]: %timeit [[i, sum([j[1] for j in a_list if j[0] == i])] for i in b_list]
1.2 µs ± 1.67 ns per loop (mean ± std. dev. of 7 runs, 1000000 loops each)

(Tutorial) Python List Comprehension, You have saved each value in a separate variable: each variable represents a single value. Instead, you store all of these values in a Python list. S is a sequence that contains values between 0 and 9 included, and each The sum() function would just do a usual sum over the entire list and assign the  Inside the loop, we are adding those elements to the total variable. # Python Program to find Sum of all Elements in a List NumList = [] total = 0 Number = int (input ("Please enter the Total Number of List Elements : ")) for i in range (1, Number + 1): value = int (input ("Please enter the Value of %d Element : " %i)) NumList.append (value) for j in range (Number): total = total + NumList [j] print (" The Sum of All Element in this List is : ", total)

An Introduction to Python Lists, And Python never creates a new list if you assign a list to a variable. For example, if a list contains numbers, the built-in sum function gives you the sum: Sort when values are None or empty strings python. python,list,sorting,null. If you want the None and '' values to appear last, you can have your key function return a tuple, so the list is sorted by the natural order of that tuple. The tuple has the form (is_none, is_empty, value); this way, the tuple for a None value will be

Loops and lists, Lists. A list is used to collect a number of values or variables in an ordered sequence. A list element can be any Python object, including numbers, strings, functions, and Implementation of a sum ∑Nj=Mq(j), where q(j) is some mathematical The file src/misc/Oxford_sun_hours.txt contains data of the number of sun  fsum () function exists in Standard math Library of Python Programming Language. The purpose of this function is, to sum up, all the values in any iterable (tuples, lists) accurately. Syntax of fsum () Function in Python The syntax of fsum () function in Python is:

How to Sum Elements of Two Lists in Python: Comprehensions and , Welcome back to another edition of the How to Python series. This time I In short, one of the best ways to sum elements of two lists in Python is to use a list Tune in next time to learn how to check if a file exists in Python. The original list is : [4, 5, 6, 3, 9] The list to be inserted is : [2, 3] The list after insertion is : [4, 5, 2, 3, 6, 3, 9] Method #2 : Using list slicing This is the most pythonic and elegant way to perform this particular task.

Comments
  • Possible duplicate of Sum list of list elements in python like sql group by
  • I reversed the duplicates because two of the answers there used groupby while a third used pandas, all of which I would consider secondary solutions to a dictionary.
  • @coldspeed: Please support your comment regarding "secondary solutions" with some explanation for the sake of readers
  • @Bazingaa groupby requires the sublists to be sorted by the grouper, so if that's not the case, there itself you lose to a dictionary in terms of time complexity. Pandas groupby is nice but also sorts keys. Dictionaries are the only solution you can use and finish this problem in linear time.
  • @user47467 This is inefficient, please don't do this.
  • @coldspeed the OP asked why their code wasn't working. This is the minimal fix to the original code that gives the desired output.
  • I'm reading the question and I don't see them explicitly ask to "fix my code". If that's the case, I would've said, "sure, this could fix your code, but.... here is a better way". It's always better to write a good answer, rather than a good enough answer.
  • To address your comment- adding an edit to the answer.
  • Whoops. Slipped out somehow. It's fixed now. Thanks for pointing it out.
  • This solution will throw a KeyError if a key is present in b_list, but not in a_list. Although OP does not explain if that can happen.
  • I don't think all of those sum calls are necessary.
  • This has the same problem as the accepted answer, looping over a_list for each key in b_list.
  • If we consider time efficiency vs simplicity, I'd prefer this one for small lists. For larger lists, it's alright to add dict or intermediate container to the code to make it more efficient.
  • A function being a compact one-liner does not make it simple. If this goes to a utility-function somewhere, it doesn't matter if it is 3 or 1 lines. One-liners are just harder to maintain and understand. For 10000 keys, your solution takes 3.82 seconds, as opposed to 0.0044 for a dictionary-solution.
  • That’s what I said for small list like the one op has it’s ok, for large list you need something better. Even the accepted answer says that op doesn’t care about time or maintainability.