tags:

views:

83

answers:

3

Simple question, i have a list if lists

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

whats the simpliest way of indexing through each list in a single for loop? For example

for i in x:
    print 1st_list_in_list
    print 2nd_list_in_list
    print 3rd_list_in_list

EDIT

Let me elaborate further, I wish to print each list how it is for example

for i in x:
    print 1st_list_in_list
    print 2nd_list_in_list

would return

1, 2, 3
4, 5, 6

+2  A: 

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
eruciform
erm its not exactly what im looking for. When I print I wish to print each list how it is for example the above code would print 1,4 and 7 but i wish to print 1,2,3
Tahira
the second one does print [1,2,3]. if you only want to go through the first one, i'll add that in a sec.
eruciform
i'm not sure which one you want - it has to be one of those three...
eruciform
+1  A: 

If you're talking about processing each element in the arrays one-by-one (I'm assuming here that the printing is just an example and your your actual desired processing is more complicated), the simplest way is to not do that. You obviously have your data structured in that way for a reason, in which case your code should mirror it.

You save very little by doing that with a single for statement so I would use:

for xlist in x:
    for n in xlist:
        do something with n

Believe it or not, having your code mirror your data actually improves code readability.

As an example, to get your exact output as specified in the edit:

#!/usr/bin/python

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

for xlist in x:
    s = ""
    for n in xlist:
        s = "%s, %c"%(s,n)
    print s[2:]
paxdiablo
+1 for "Believe it or not, having your code mirror your data actually improves code readability."
Achim
+5  A: 

Try this:

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

Output:

1, 2, 3
4, 5, 6
7, 8, 9
Mark Byers