jeffng50
jeffng50

Reputation: 302

Looping a list of lists, while accessing each elements easily

I apologise in advance if this has been answered before, I didn't know what to search for.

Say, I want to iterate through a list of lists that looks like this:

x = [[a, b, c], [a, b, c], ...]

I figured out I can do this to easily access the lists inside that structure:

for [a, b, c] in x:
        doSomethingToElements(a,b,c)

What I want to do is:

for [a, b, c] as wholeList in x:
        doSomethingToElements(a,b,c)
        doSomethingToWholeLists(wholeList)

However, that syntax is invalid, is there any equivalent way to do it, which is correct and valid? Or should I do it with enumerate() as stated here?

EDIT: Working through to make enumerate() work, I realise I can do this:

for idx, [a, b, c] in enumerate(x):
        doSomethingToElements(a,b,c)
        doSomethingToWholeLists(x[idx])

But feel free to post more elegant solutions, or is it elegant enough that it doesn't matter?

Upvotes: 1

Views: 31

Answers (2)

wim
wim

Reputation: 362796

There is not really any syntax similar to that suggestion. Your best bet would be splat-unpacking:

for wholeList in x:
    doSomethingToElements(*wholeList)
    doSomethingToWholeLists(wholeList)

Upvotes: 1

Gilseung Ahn
Gilseung Ahn

Reputation: 2624

There are two options. The first one is iterate element and list together using zip, and the second one is iterate the list and assign each value.

x = [[1, 2, 3], [4, 5, 6]]
for (a, b, c), z in zip(x, x):
    print(a, b, c, z)

for z in x:
    a, b, c = z
    print(a, b, c, z)

Upvotes: 1

Related Questions