0

I have a question about list concatenation in Python, I have this piece of code:

def lista():
    word = sys.argv[1]
    l = []
    m = []
    for file_name in sys.argv[2:]:
        with open(file_name, "r") as f:
            for line in f:
                l + [len(re.findall(word, line))] #doesn't work
                m.append(len(re.findall(word, line))) #works
    print l
    print m
    return l 

when I run this function I always get empty list l, but there are elements in m, why l+[elem] doesen't work for me?

1

4 Answers 4

4

You are never assigning a new value to l. You should use assignment. Try calling l = l + [len(re.findall(word,line))]

EDIT: another option is to use the += opertor: l+=[len(re.findall(word,line))]

Sign up to request clarification or add additional context in comments.

Comments

3

Because l+[len(re.findall(word,line))] is just adding the two list but throwing away the result. You probably want

l+=[len(re.findall(word,line))]

General observations:

  • Your variable names are not according to PEP-8
  • Appending a list is costly and generally not pythonic. You can use a generator for this purpose.
  • You should use a with statement with files, to ensure it is closed even if an exception occurs.

Here is the Program with suggested edits.

def lista():
    word=sys.argv[1]
    def search():
        for file_name in sys.argv[2:]:
            with open(file_name,"r") as fin:
                for line in fin:
                    yield len(re.findall(word,line))
    return [l for l in search()]

Comments

2

Here you want to just use l.append() - what you are doing has the same effect, except it's less readable and slower.

python -m timeit -s "l=[]" "for i in range(1000):" "  l.append(i)"
10000 loops, best of 3: 106 usec per loop

python -m timeit -s "l=[]" "for i in range(1000):" "  l += [i]"
10000 loops, best of 3: 124 usec per loop

Comments

1
l = l+[len(re.findall(word,line))] #works

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.