1

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?

jeffng50
  • 199
  • 3
  • 15

2 Answers2

1

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)
Gilseung Ahn
  • 2,598
  • 1
  • 4
  • 11
  • I'm not sure about the zip solution, but yeah the second one is pretty simple i like it – jeffng50 Oct 06 '20 at 01:31
  • I feel that this is a good enough solution, that is simple, hence I grant you the accepted answer badge. Also, for any future aspiring developers that encounter this issue but needn't use all three ```a,b,c``` elements, you can use ```_``` for unnecessary ones – jeffng50 Oct 06 '20 at 01:40
1

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)
wim
  • 338,267
  • 99
  • 616
  • 750
  • I guess this only works when you pass it through a function right? What if I want to manipulate a,b or c at the spot without a function? – jeffng50 Oct 06 '20 at 01:30
  • 1
    It works in a few other contexts, e.g. `padded_wholeList = ["pre", *wholeList, "post"]`, but function call syntax is the most common usage. If you want the local variables within the loop, just assign them: `a, b, c = wholeList` – wim Oct 06 '20 at 01:49