-2
tokens=[[1,2,3],[4,5,6],[7,8,9]]     
for k in [m for m in tokens]:
         print(k)

how to change " for loop" to just one list comprehension by Python3?

snakecharmerb
  • 47,570
  • 11
  • 100
  • 153

5 Answers5

0

As far as I understood your question your are trying to put every element in tokens in a new list:

kList = []                 #new empty list
for m in tokens:           #main list
    for k in m:            #sub-lists
        kList.append(k)
print(kList)               #output
T. Feix
  • 179
  • 11
0

You could do a simple for loop to add them into one list:

tokens=[[1,2,3],[4,5,6],[7,8,9]]
token_unified = []

for k in tokens:
         token_unified += (k)

print(token_unified)

Output: [1, 2, 3, 4, 5, 6, 7, 8, 9]

T. Feix
  • 179
  • 11
Phillip Geltman
  • 195
  • 1
  • 13
0
tokens=[[1,2,3],[4,5,6],[7,8,9]]
print(*tokens, sep='\n')

Output:

[1, 2, 3]
[4, 5, 6]
[7, 8, 9]

Single line code for your expected output.

Vashdev Heerani
  • 660
  • 7
  • 21
-1

Try this:

[print(j) for i in tokens for j in i]                                                            

Or if you want it printed in list format:

print([j for i in tokens for j in i])

Edit: Not sure why this got downvoted. I assume OP's asking to print all values in the nested list using list comprehensions. If they want to return a list, you could just modify the above code to assign the list to a variable.

tokens_flattened = [j for i in tokens for j in i]
Ladi Oyeleye
  • 154
  • 4
-1

First, try to print what your list comprehension is holding. [m for m in tokens] is nothing but your tokens. Now, whatever operation you want to perform on m for every m in tokens, perform on the first m of your list comprehension as it is a single currently selected element of the list in your loop.

The solution to your problem is as follows:

tokens=[[1,2,3],[4,5,6],[7,8,9]]
[print(m) for m in tokens]

This will give you the following output:

[1, 2, 3]
[4, 5, 6]
[7, 8, 9]

If you want to print out single elements as a list, do the following:

tokens=[[1,2,3],[4,5,6],[7,8,9]]  
ans = []   
[ans.extend(m) for m in tokens]
print(ans)

It will give you the following output:

[1, 2, 3, 4, 5, 6, 7, 8, 9]
Manmay Barot
  • 165
  • 1
  • 8