Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to iterate over a list of lists and print items of each list as a comma-delimited string

Tags:

python

list

If I have a list of lists:

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

How do I iterate over these lists and print them to get the following output?

1, 2, 3
4, 5, 6
7, 8, 9
like image 523
Tahira Avatar asked Dec 04 '22 12:12

Tahira


2 Answers

Try this:

for l in x:
    print ', '.join(map(str, l))

Output:

1, 2, 3
4, 5, 6
7, 8, 9
like image 177
Mark Byers Avatar answered May 25 '23 00:05

Mark Byers


You pretty much have it:

# python
x = [['1','2','3'],['4','5','6'],['7','8','9']]

for i in x:
  print i[0]
1
4
7

for i in x:
  print i
['1', '2', '3']
['4', '5', '6']
['7', '8', '9']

for i in x[0]:
  print i
1
2
3
like image 22
eruciform Avatar answered May 24 '23 23:05

eruciform