# Trying To Add Duplicates Within A List Of Lists In Order

## 17 March 2022 - 1 answer

I have two separate lists within a list.. I am trying to count duplicates within the second list. I can do it from list a to list b, with the result:

``````count_list = [['about', 1], ['almost', 1], ['apple', 1], ['break', 1], ['Singapore', 1], ['cider', 1], ['up', 1], ['day', 1]]
first_proc_count = [['turn', 1], ['there', 1], ['pear', 1], ['up', 1], ['XXXXXX', 0], ['drink', 1], ['near', 1], ['up', 1]]

for word in first_proc_count:
for word2 in count_list:
if word[0] == word2[0]:
word[1] = word[1] + word2[1]
word2[1] = 0

print(count_list)
print(first_proc_count)
``````

with the result -[['about', 1], ['almost', 1], ['apple', 1], ['break', 1], ['Singapore', 1], ['cider', 1], ['up', 0], ['day', 1]] -[['turn', 1], ['there', 1], ['pear', 1], ['up', 2], ['XXXXXX', 0], ['drink', 1], ['near', 1], ['up', 1]]

with the word “up” being added to 2nd list and “up” being set to 0 in the first.

But I am having a problem doing the same within the second list ie. with a single list. I know I should increment the loop by one and look in the incremented loop. The result I would hope for is:

[['turn', 1], ['there', 1], ['pear', 1], ['up', 3], ['XXXXXX', 0], ['drink', 1], ['near', 1], ['up', 0]]

I have tried a range and length with an += 1 but I’m getting nowhere. First ever question here. Excuse the bad formatting. Thanks.

Currently the problem is that you're comparing the list to itself twice over. The following code should fix this:

``````count_list = [['about', 1], ['almost', 1], ['apple', 1], ['break', 1], ['Singapore', 1], ['cider', 1], ['up', 1], ['day', 1]]
first_proc_count = [['turn', 1], ['there', 1], ['pear', 1], ['up', 1], ['XXXXXX', 0], ['drink', 1], ['near', 1], ['up', 1]]

for i in range(len(first_proc_count)):
for word2 in first_proc_count[i + 1:]:
if first_proc_count[i][0] == word2[0]:
first_proc_count[i][1] = first_proc_count[i][1] + word2[1]
word2[1] = 0

print(count_list)
print(first_proc_count)
``````