0

I'm pretty new to Python and am trying to work through a list of lists.

Say I have:

myList = [[1,2,3,4],[10,11,12,13],[29,28,27,26]]

and a function called myFunction

I could write:

for x in myList:
   for y in x:
     myFunction(y)

However, that would just call myFunction on each individual item in all the sublists. How would I incorporate something that I could also call when I finish up all the items in each sublist (e.g. I would call 1, 2, 3 and 4, and then the loop would realize it is at the end of the sublist and I could call that sublist).

Thanks so much!

3 Answers 3

5

Do what you want in outer loop:

>>> for x in myList:
...     for y in x:
...         print(y)
...     print(x) # <---
...
1
2
3
4
[1, 2, 3, 4]
10
11
12
13
[10, 11, 12, 13]
29
28
27
26
[29, 28, 27, 26]
Sign up to request clarification or add additional context in comments.

2 Comments

Thanks! What if what I would want to do in the outer loop can only be done once the item in the inner loop has been completed? In this case, I would want to work on the items in the inner loop for each sublist, then call the sublist, then move on to the items in the next sublist.
@John, In the above code, print(x) is only executed only after the inner loop has been completed.
1

John, it is indented syntax of Python, while it is indented it is a block of code, i.e. all commands are in pack (in block):

for x in myList:
    # block of code started
    for y in x:
        # here is new block
        # some here will be called totally "all elements in all sublists" times
        # i.e. "number of elements in x" times 
        # per "number of sublist in myList" times
        # and here will be called the same number of times (it is block)
    # here you're out of "for y in x" loop now (you're in previous block)
    # some here will be called "myList" number of times 
    # and here
# here you are out of "for x in myList" loop

Comments

0

Hope this is what you want:

def myFunction(y):
    print y

myList = [[1,2,3,4],[10,11,12,13],[29,28,27,26]]

for x in range(len(myList)):
   print "Sublist:",x, myList[x]
   for y in myList[x]:
     myFunction(y)

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.