Creating a list of lists using list comprehension

Viewed 484

I need to create a code using list comprehension that looks at a predetermined list X = [5,6,7] and creates a new list that includes a list of the powers of X, the powers being from 0 to k. I was able to write the code that could create the powers of X however when I run my code instead of receiving the desired output:

[[1, 5, 25], [1, 6, 36], [1, 7, 49]]

I receive this: [[1, 5, 25, 1, 6, 36, 1, 7, 49]]

Here is the code I am running,

[[i**j for i in X for j in range(k+1)]]

I've tried fiddling with the bracket placement but when I change the brackets to contain only [i**j] the results become even more peculiar: [[1], [5], [25], [1], [6], [36], [1], [7], [49]]

Any help or advice would be greatly appreciated!

4 Answers

You need to nest the list comprehensions.

[[i**j for j in range(k+1)] for i in X]

In list comp, the outer loop is executed first and based on the number the nested loop is executed.

[[pow(number,power) for power in range(k+1)] for number in x]

Nested list comprehension need to be used.

res = [[num ** i for i in range(k+1)] for num in x]

list comprehension '[num ** i for i in range(k+1)]' is run for every number in 'x'. This creates a list for the powers of 0 to k for every number in x.

X = [5,6,7]

# list comprehension: lst = [<obj-expression> for <obj> in <iterable>]

# using divide-and-conquer technique,
# I am able to make the list as following:
lst1 = []
for x in X:
    lst1.append([x**i for i in range(0, 3)])
print(lst1)

# Now, I can combine them together using the list comprehension definition:
lst2 = [[x**i for i in range(0, 3)] for x in X]
print(lst2)
Related