Python - Extended sequence assignment in for loops

Introduction

You can use Python 3.X's extended sequence-unpacking assignment syntax to extract items and sections of sequences within sequences.

Demo

a, b, c = (1, 2, 3)                               # Tuple assignment 
# from ww  w .j  av  a 2 s .  co  m
for (a, b, c) in [(1, 2, 3), (4, 5, 6)]:          # Used in for loop 
     print(a, b, c)

Result

In Python 3.X, a sequence can be assigned to a more general set of names with a starred name to collect multiple items.

We can use the same syntax to extract parts of nested sequences in the for loop:

Demo

a, *b, c = (1, 2, 3, 4)                           # Extended seq assignment 
# ww w .java 2s. c o  m
for (a, *b, c) in [(1, 2, 3, 4), (5, 6, 7, 8)]: 
    print(a, b, c)

Result

Related Example