[Python Tips] Destructuring

This is an easy tip, but an extremely useful feature of Python.

Destructuring lists

Let's take the following sample list:

my_list = ['a', 'b','c']

I want to put each list element into their own variable, you could write a for loop or iterate through the list to create a variable for each element.

Destructuring to the rescue

a, b, c = my_list

That's it!

Real world example

This is all cool and so on, but want to see it in action?

Latest Block

Let's grab the latest block on the Steem blockchain.
Full Block Displayed Here

Transactions in block

First, we want to get just the transactions in the block.
(I am going to skip some for loops and just focus on an individual transaction)

transactions = block['transactions']

If we look at the first transaction we get something like this:

{
'ref_block_num': 50957,
'ref_block_prefix': 355189199,
'expiration': '2018-04-27T18:09:24',
'operations': [
[
'vote',
{
'voter': 'loradavis',
'author': 'veseloff',
'permlink': 'the-deal-coin-innovative-solution -for-business-lending',
'weight': 10000
}
]
],
'extensions': [

],
'signatures': [
'20198cf4469c494880329cc9966fa070e022ab134e09f03f9d9213809f8a4ac207744c79c8dbbdf4976ac0a330977df97ba534d764c45b9cf87ea37f461f075a15 '
]
}

Operations in transaction

We are concerned with the operations section.

operations = transaction['operations']

This will give us all operations for a particular transaction. This is typically only one operation like this:

[
[
'vote',
{
'voter': 'loradavis',
'author': 'veseloff',
'permlink': 'the-deal-coin-innovative-solution-for-business-lending',
'weight': 10000
}
]
]

Operation Type & Operation from Operation

If you look carefully you will see there are two pieces of the initial list, the operation type, and the operation. Let's use destructuring here to break this up quickly and easily from the first (and likely only) operation.

op_type, op = operations[0]

print(op_type)
>> 'vote`
print(op)
>> {'voter': 'loradavis', 'author': 'veseloff', 'permlink': 'the-deal-coin-innovative-solution-for-business-lending', 'weight': 10000}

Taking it further

You can break down the operation using destructuring as well if you wanted to.

Data in op

{'voter': 'loradavis', 'author': 'veseloff', 'permlink': 'the-deal-coin-innovative-solution-for-business-lending', 'weight': 10000}

Destucturing op

voter, author, permlink, weight = op

Conclusion

Destructuring is a powerful Python tool that when used properly can make your code easier to read and easier to write. It works best for data sets that have only a few elements and wouldn't work well destructuring into 10-20+ variables. When working on with data sets with 2-5 elements, it's a really nice tool to have in your toolbox.

My Python Tips Series

H2
H3
H4
3 columns
2 columns
1 column
18 Comments
Ecency