Search
 
SCRIPT & CODE EXAMPLE
 
CODE EXAMPLE FOR PYTHON

python destructuring

x, y = (5, 11)

people = [
  ("James", 42, "M"),
  ("Bob", 24, "M"),
  ("Ana", 32, "F")
]

for name, age, gender in people:
  print(f"Name: {name}, Age: {age}, Profession: {gender}")

# use _ to ignore a value
person = ("Bob", 42, "Mechanic")
name, _, profession = person

head, *tail = [1, 2, 3, 4, 5]

print(head)  # 1
print(tail)  # [2, 3, 4, 5]

*head, tail = [1, 2, 3, 4, 5]

print(head)  # [1, 2, 3, 4]
print(tail)  # 5

head, *middle, tail = [1, 2, 3, 4, 5]

print(head)    # 1
print(middle)  # [2, 3, 4]
print(tail)    # 5

head, *_, tail = [1, 2, 3, 4, 5]
print(head, tail)  # 1 5

from operator import itemgetter

params = {'a': 1, 'b': 2, 'c': 3}

# return keys a and c
a, c = itemgetter('a', 'c')(params)

print(a, c)
# output 1 3
Source by codefreelance.net #
 
PREVIOUS NEXT
Tagged: #python #destructuring
ADD COMMENT
Topic
Name
9+1 =