2

For the following nested list, Lst, I need to keep the first inner list, square the second, and cube the last one.

Lst = [[1,2,3],[2,3,4],[3,4,5]]

My current code is squaring all the nested list in the Lst.

list(map(lambda lst: list(map(lambda x: x**2, lst)), Lst))

How can I fix this? I just started learning Python.

1
  • Please update your question with the output you require. Commented Jul 10, 2021 at 17:03

4 Answers 4

4

Since you're not doing the same operation on each nested list, you shouldn't use map() for the top-level list. Just make a list of results of different mappings for each.

[Lst[0], list(map(lambda x: x**2, lst[1])), list(map(lambda x: x**3, lst[2]))]

However, there's an obvious pattern to this, so you can generalize it using enumerate() and a list comprehension:

[list(map(lambda x: x**i, sublist)) for i, sublist in enumerate(Lst, 1)]
Sign up to request clarification or add additional context in comments.

Comments

1
[list(map(lambda x: x**i, l)) for i,l in enumerate(Lst, 1)]
[[1, 2, 3], [4, 9, 16], [27, 64, 125]]

Comments

0

Your processing obviously needs to take into account where in the list you are. Forcing this into a one-liner makes it more dense than it really needs to be, but see if you can follow along with pencil and paper.

[[x if i == 0 else x**2 if i == 1 else x**3 for x in Lst[i]] for i in range(3)]

Demo: https://ideone.com/o8y0ta

... Or, as cleverly suggested in Barmar's answer,

[[x**i for x in Lst[i]] for i in range(3)]

Comments

0

Try indexing the outer list and then call the map function on each index

def square(number) :
    return number ** 2
def cube(number) :
    return number ** 3

lst = [[1,2,3],[2,3,4],[3,4,5]]

lst[0] = lst[0]
lst[1] = list(map(square, lst[1]))
lst[2] = list(map(cube, lst[2]))

print(lst)

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.