user225312
user225312

Reputation: 131677

Modifying nested lists

How to handle nested lists in Python? I am having problem figuring out the syntax. Like example:

>>> l = [[1, 2, 3], [5, 6, 7]]

I want to square all the elements in this list. I tried:

[m*m for m in l]

But that doesn't work and throws up:

TypeError: can't multiply sequence by non-int of type 'list'

because of the nested lists I guess?

How do I fix this?

Upvotes: 2

Views: 2731

Answers (4)

Tyler Eaves
Tyler Eaves

Reputation: 13121

[[1,2,3],[4,5,6]] != [1,2,3,4,5,6]    

[map(lambda x: x *x,sl) for sl in l]    #List comprhension

Upvotes: 1

jgritty
jgritty

Reputation: 11925

Assuming you wanted the answer to look like this:

[[1, 4, 9], [25, 36, 49]]

You could do something like this:

l = [[1, 2, 3], [5, 6, 7]]

for x in range(len(l)):
    for y in range(len(l[x])):
        l[x][y] = l[x][y] * l[x][y]

print l

Obviously, the list comprehension answer is better.

Upvotes: 1

Matti Virkkunen
Matti Virkkunen

Reputation: 65126

What you need is a recursive function, something like this:

def square(el):
    if type(el) == list:
        return [square(x) for x in el]
    else:
        return el**2;

I'd rather not get into the correctness of type(el) == list here, but you get the gist.

Of course, this is also doable with a list-comprehension, as many people have pointer out, provided that the structure is always the same. This recursive function can handle any level of recursion, and lists containing both lists and numbers.

Upvotes: 0

user225312
user225312

Reputation: 131677

>>> l = [[1, 2, 3], [5, 6, 7]]
>>> [[e*e for e in m] for m in l]
     |-nested list-|
    |----   complete list    ---|
[[1, 4, 9], [25, 36, 49]]

Upvotes: 9

Related Questions