http8086
http8086

Reputation: 1686

How to understand the list comprehensions in making list in python?

I have a list of tuples, which will be converted to another list which has elements of list type, since each element is a list, we can insert the natural number at the head. Let's put:

    l = [('c++', 'compiled'), ('python', 'interpreted')]
    lx = []
    for z in xrange(len(l)):
        y = [x for x in l[z]]
        y.insert(0, z)
        lx.append(y)
    print lx
    [[0, 'c++', 'compiled'], [1, 'python', 'interpreted']]

Look, job done, it works in that way. Except any of the followings

Neither:

    l = [('c++', 'compiled'), ('python', 'interpreted')]
    lx = []
    for z in xrange(len(l)):
        y = [x for x in l[z]]
        lx.append(y.insert(0, z))
    print lx
    [None, None]

Nor:

    l = [('c++', 'compiled'), ('python', 'interpreted')]
    lx = []
    for z in xrange(len(l)):
        y = [x for x in l[z]].insert(0, z)
        lx.append(y)
    print lx
    [None, None]

Not to mention:

    l = [('c++', 'compiled'), ('python', 'interpreted')]
    lx = []
    for z in xrange(len(l)):
        lx.append([x for x in l[z]].insert(0, z))
    print lx
    [None, None]

Works, why is that? I noticed such as:

y = [x for x in l[z]]

is no one cycle execution in debug step by step, which is just beyond my impression of expression in other languages.

Upvotes: 0

Views: 55

Answers (1)

BartoszKP
BartoszKP

Reputation: 35891

The insert method does not return anything, which in Python is equivalent of returning the None constant. So, for example after this line:

y = [x for x in l[z]].insert(0, z)

y will always be None. And that is what you append to lx, hence the result. Your first snippet is the correct approach. The question has nothing to do with list-comprehensions.

Upvotes: 5

Related Questions