Find anagrams of a word in a list I'm just starting to learn programming again after a long break and decided on Python. Here's my code:

#"Code Wars: Where my anagrams at?" A program that finds all anagrams of "word" in "wordList".

import copy

def anagrams(word, wordList):
    result = [] #List to store all the anagrams.
    for i in wordList:  #Outer loop finds all anagrams of "word".
        source = copy.deepcopy(list(i))   #Creates a copy of the current word in the word list as a list.
        var = True #Boolean value that indicates whether "i" is an anagram of "word" or not.
        for j in word:  #Inner loop. It checks if "i" is an anagram of "word".
            if(j in source):    #Incrementally deletes the matching characters.
                source.remove(j)
            else:   #Early exit if a single character in "word" is missing from "i".
                var = False
                break
        if(source != []):    #If "i" is an anagram of "word", then "source" should be empty.
            var = False
        if(var):   #Add the word to the result list iff "i" is an anagram of "word".
            result.append(i)
    return(result)


What am I doing wrong (re best practices/design/efficiency)?
What could I do better?
The most pythonic way (IMO) to check if two words are anagrams of each other is to check if the number of times each letter appears in each words is the same. For this you can use collections.Counter:

from collections import Counter

&gt;&gt;&gt; Counter("test")
Counter({'e': 1, 's': 1, 't': 2})


With this we can re-write your function to :

def anagrams(word, words):
    result = []
    counter_word = Counter(word)
    for other_word in words:
        if Counter(other_word) == counter_word:
            result.append(other_word)
    return result


This is a lot more readable. in addition, here are some more comments on your code itself:


source = copy.deepcopy(list(i)) is not needed. Since strings are immutable, just doing list(i) would have been fine.
In if(j in source): there are two things:


Python has an official style-guide, PEP8, which is well worth a read. It recommends not using parenthesis in if (and while) statements, so this should be if j in source
in is \$\mathcal{O}(n)\$ for lists and strings, so this is actually quite an expensive way to do it. The better way is using a dictionary (collections.Counter is a dictionary plus some nice stuff).

In for i in wordList, again, PEP8 has something to say, it should be word_list, or even easier words. Also i is not a good name.


Depending on what you want to do afterwards with the anagrams, you could also make this a generator (which you can iterate over and which continuesly yields anagrams):

def anagrams(word, words):
    counter_word = Counter(word)
    for other_word in words:
        if Counter(other_word) == counter_word:
            yield other_word