avatarChristopher Tao

Free AI web copilot to create summaries, insights and extended knowledge, download it at here

8381

Abstract

than one list in one go.</p><div id="255e"><pre><span class="hljs-function"><span class="hljs-title">print</span><span class="hljs-params">(*[<span class="hljs-string">'Alice'</span>, <span class="hljs-string">'Bob'</span>], [<span class="hljs-string">'Chris'</span>], <span class="hljs-string">'David'</span>)</span></span></pre></div><figure id="dd5f"><img src="https://cdn-images-1.readmedium.com/v2/resize:fit:800/1*sEGFD4z4aBiJ-6E5sFvx4Q.png"><figcaption></figcaption></figure><p id="7acd">To combine multiple lists with some loose items, we can also use asterisks to unpack the lists.</p><div id="14fa"><pre>[<span class="hljs-name"><span class="hljs-built_in"></span></span>[<span class="hljs-symbol">'Alice</span>', <span class="hljs-symbol">'Bob</span>'], [<span class="hljs-symbol">'Chris</span>'], <span class="hljs-symbol">'David</span>']</pre></div><p id="886c">This trick can also be used when we want to put multiple lists into a tuple or a set.</p><div id="43cf"><pre>([<span class="hljs-string">'Alice'</span>, <span class="hljs-string">'Bob'</span>], [<span class="hljs-string">'Chris'</span>], <span class="hljs-string">'David'</span>) {[<span class="hljs-string">'Alice'</span>, <span class="hljs-string">'Bob'</span>, <span class="hljs-string">'Chris'</span>], [<span class="hljs-string">'Chris'</span>], <span class="hljs-string">'David'</span>, <span class="hljs-string">'Chris'</span>}</pre></div><figure id="20e3"><img src="https://cdn-images-1.readmedium.com/v2/resize:fit:800/1*YsrO-NhZp1uH_u_B_Y40Xw.png"><figcaption></figcaption></figure><p id="fc92">Now, let’s consider a more advanced use case. We have got a 2-D list as follows. Each sub-list has two items, a name and an age. It is not easy to use so we want to transpose the 2-D list so that one list has all the names and the other one has all the ages.</p><div id="2dab"><pre>my_list = [ [<span class="hljs-string">'Alice'</span>, <span class="hljs-number">31</span>], [<span class="hljs-string">'Bob'</span>, <span class="hljs-number">32</span>], [<span class="hljs-string">'Chris'</span>, <span class="hljs-number">33</span>] ]</pre></div><p id="ed91">The easiest way to do this is to unpack the list in a <code>zip()</code> function.</p><div id="08b4"><pre><span class="hljs-variable">for</span> <span class="hljs-variable">i</span> <span class="hljs-variable"><span class="hljs-keyword">in</span></span> <span class="hljs-function"><span class="hljs-title">zip</span>(<span class="hljs-variable">my_list</span>): <span class="hljs-title">print</span>(<span class="hljs-title">list</span>(<span class="hljs-variable">i</span>))</span></pre></div><figure id="d8e6"><img src="https://cdn-images-1.readmedium.com/v2/resize:fit:800/1*x44CaIY7YDpITjmRWr6WYQ.png"><figcaption></figcaption></figure><p id="78d0">This is equivalent to doing such.</p><div id="a41e"><pre><span class="hljs-keyword">for</span> <span class="hljs-selector-tag">i</span> <span class="hljs-keyword">in</span> <span class="hljs-built_in">zip</span>(<span class="hljs-selector-attr">[<span class="hljs-string">'Alice'</span>, 31]</span>, <span class="hljs-selector-attr">[<span class="hljs-string">'Bob'</span>, 32]</span>, <span class="hljs-selector-attr">[<span class="hljs-string">'Chris'</span>, 33]</span>): <span class="hljs-built_in">print</span>(i)</pre></div><figure id="7a26"><img src="https://cdn-images-1.readmedium.com/v2/resize:fit:800/1*3AAwg0aC8LBqhXdN5UvzrA.png"><figcaption></figcaption></figure><p id="f26c">If we still want a 2-D list, we can put the two sub-lists into a parent list using list comprehension.</p><div id="e4b0"><pre>[<span class="hljs-name"><span class="hljs-built_in">list</span></span>(<span class="hljs-name">i</span>) for i in zip(<span class="hljs-name">*my_list</span>)]</pre></div><figure id="e37c"><img src="https://cdn-images-1.readmedium.com/v2/resize:fit:800/1*S8qJW0h8V56108DTU7V5zw.png"><figcaption></figcaption></figure><p id="0f9d">If you are not quite familiar with the <code>zip()</code> function, please check out one of my previous articles that deep dive into this.</p><div id="b2d1" class="link-block"> <a href="https://towardsdatascience.com/fasten-python-objects-using-zip-88a1e7a68c7"> <div> <div> <h2>“Fasten” Python Objects Using Zip</h2> <div><h3>A Python trick makes the usage of multiple iterables easier</h3></div> <div><p>towardsdatascience.com</p></div> </div> <div> <div style="background-image: url(https://miro.readmedium.com/v2/resize:fit:320/1*yIgnQTYq21mXFKOF5w2dSw.jpeg)"></div> </div> </div> </a> </div><h2 id="ab76">3.2 Unpacking Dictionary</h2><p id="c9bd">Since Python 3.5, the asterisks can also unpack dictionaries, but we need to put double asterisks in front of the dictionary variable to unpack it.</p><p id="f8f1">One of the most common usages would be combining multiple dictionaries together. Suppose we have two dictionaries as follows to be combined, we can unpack them and put them inside another empty dictionary.</p><div id="f0a1"><pre>my_dict1 = { 'name': 'Chris', 'age': <span class="hljs-number">33</span> }</pre></div><div id="0af0"><pre>my_dict2 = { 'skill': 'Python' }</pre></div><div id="c350"><pre><span class="hljs-attr">my_dict</span> = {**my_dict1, **my_dict2}</pre></div><figure id="e835"><img src="https://cdn-images-1.readmedium.com/v2/resize:fit:800/1*GAxANAsrfLi1RifL5rJ90w.png"><figcaption></figcaption></figure><p id="5e26">Another sample usage pattern will be the format string. Although I love the f-string syntax in Python, the format string still has some advantages. For example, it allows the parameterised string with parameter names.</p><div id="f178"><pre><span class="hljs-string">"My name is {name}. I'm {age} years old and I can use {skill}"</span>.format( <span class="hljs-attribute">name</span>=<span class="hljs-string">'Chris'</span>, <span class="hljs-attribute">age</span>=33, <span class="hljs-attribute">skill</span>=<span class="hljs-string">'Python'</span> )</pre></div><figure id="fee1"><img src="https://cdn-images-1.readmedium.com/v2/resize:fit:800/1*55yYoqSopUu8b-1HtpiaXg.png"><figcaption></figcaption></figure><p id="bca4">In this case, we can unpack the previous dictionary and put it in the format string to pass the arguments.</p><div id="9148"><pre><span class="language-xml">"My name is </span><span class="hljs-template-variable">{name}</span><span class="language-xml">. I'm </span><span class="hljs-template-variable">{age}</span><span class="language-xml"> years old and I can use </span><span class="hljs-template-variable">{skill}</span><span class="language-xml">".format(**my_dict)</span></pre></div><figure id="4d01"><img src="https://cdn-images-1.readmedium.com/v2/resize:fit:800/1*BNFiyoExOaENMGfih-hSFA.png"><figcaption></figcaption></figure><p id="e761">This is very neat and clean. Also, we can even unpack multiple dictionaries into this.</p><div id="fff0"><pre><span class="language-xml">"My name is </span><span class="hljs-template-variable">{name}</span><span class="language-xml">. I'm </span><span class="hljs-template-variable">{age}</span><span class="language-xml"> years old and I can use </span><span class="hljs-template-variable">{skill}</span><span class="language-xml">".format(**my_dict1, **my_dict2)</span></pre></div><figure id="c04d"><img src="https://cdn-images-1.readmedium.com/v2/resize:fit:800/1*8_oeL-pNJCOziWCk0iv-lw.png"><figcaption></figcaption></figure><h2 id="52e1">3.3 Unpack Range</h2><p id="031e">One of the usages that are not very common of using asterisks for unpacking is for a Python range. We usually use <code>range()</code> to tell a for-loop how many times it needs to be looped. We can also use it to generate a range of sequential numbers as follow.</p><div id="8bfc"><pre><span class="hljs-function"><span class="hljs-title">list</span>(<span class="hljs-title">range</span>(<span class="hljs-number">10</span>))</span></pre></div><figure id="b5f7"><img src="https://cdn-images-1.readmedium.com/v2/resize:fit:800/1*Fn1e5Xdj60ldXhBW2-O8lg.png"><figcaption></figcaption></figure><p id="c686">Syntactically, we can also use an asterisk to unpack the range object, though I don’t think there are any be

Options

nefits in this case.</p><div id="17dc"><pre>[<span class="hljs-name">*range</span>(<span class="hljs-name">10</span>)]</pre></div><figure id="6425"><img src="https://cdn-images-1.readmedium.com/v2/resize:fit:800/1*aqrEJWxihEldzUID_B8Y1Q.png"><figcaption></figcaption></figure><h1 id="44c8">4. List Packing Up</h1><figure id="da97"><img src="https://cdn-images-1.readmedium.com/v2/resize:fit:800/1*UaQHQQ-9FugjRmSfYMJ5Bg.jpeg"><figcaption>Image by <a href="https://pixabay.com/users/kriemer-932379/?utm_source=link-attribution&amp;utm_medium=referral&amp;utm_campaign=image&amp;utm_content=1619751">Kerstin Riemer</a> from <a href="https://pixabay.com/?utm_source=link-attribution&amp;utm_medium=referral&amp;utm_campaign=image&amp;utm_content=1619751">Pixabay</a></figcaption></figure><p id="5287">Yes, we can not only unpack lists using asterisks but also pack items up in some scenarios. For example, we can use the following syntax to use 3 variables for getting 3 items from a list respectively.</p><div id="95ec"><pre><span class="hljs-attr">students</span> = [<span class="hljs-string">'Alice'</span>, <span class="hljs-string">'Bob'</span>, <span class="hljs-string">'Chris'</span>]</pre></div><div id="032f"><pre>my_classmate1, my_classmate2, <span class="hljs-keyword">me</span> = students</pre></div><figure id="9974"><img src="https://cdn-images-1.readmedium.com/v2/resize:fit:800/1*kleeZca2VLxL-DRXztW5vQ.png"><figcaption></figcaption></figure><p id="b9c6">Suppose in the above case, it doesn’t matter who are my classmates, we just want my name at the last and all the other names should remain in a list. In this case, we can use an asterisk to pack all the other items up.</p><div id="edc8"><pre><span class="hljs-attribute">students</span> = [<span class="hljs-string">'Alice'</span>, <span class="hljs-string">'Bob'</span>, <span class="hljs-string">'Chris'</span>] *other_students, me = students</pre></div><figure id="ee78"><img src="https://cdn-images-1.readmedium.com/v2/resize:fit:800/1*x0Gt3msPAv7APc3a8z06tw.png"><figcaption></figcaption></figure><p id="4a82">You may know that the syntax is also applicable for a tuple. However, it needs to be noticed that using an asterisk for packing up the items will always return a list. In other words, it cannot be smart enough to return a tuple, though the original object is a tuple</p><div id="0d11"><pre><span class="hljs-attribute">students</span> = (<span class="hljs-string">'Alice'</span>, <span class="hljs-string">'Bob'</span>, <span class="hljs-string">'Chris'</span>) *other_students, me = students</pre></div><div id="c9d9"><pre><span class="hljs-function"><span class="hljs-title">print</span><span class="hljs-params">(me)</span></span> <span class="hljs-function"><span class="hljs-title">print</span><span class="hljs-params">(other_students)</span></span></pre></div><figure id="f3c3"><img src="https://cdn-images-1.readmedium.com/v2/resize:fit:800/1*KKpz1MCYv-N1NI6H7qb0uQ.png"><figcaption></figcaption></figure><p id="aa50">Using this trick, we can also treat a string as a list of characters and get some particular ones with all the others packed up.</p><div id="9471"><pre>product<span class="hljs-number"></span>code = <span class="hljs-string">'A320'</span> <span class="hljs-keyword">class</span><span class="hljs-number"></span>indicator, *model = product<span class="hljs-number">_</span>code</pre></div><div id="9662"><pre><span class="hljs-function"><span class="hljs-title">print</span><span class="hljs-params">(<span class="hljs-string">'Class indicator: '</span>, class_indicator)</span></span> <span class="hljs-function"><span class="hljs-title">print</span><span class="hljs-params">(<span class="hljs-string">'Model:'</span>, <span class="hljs-string">''</span>.join(model)</span></span>)</pre></div><figure id="674c"><img src="https://cdn-images-1.readmedium.com/v2/resize:fit:800/1*3m3MMMaEeVQ316pKd3zTHw.png"><figcaption></figcaption></figure><p id="62a1">This is for demo purposes again, since I definitely believe using slicing is easier and more readable.</p><div id="0751"><pre><span class="hljs-function"><span class="hljs-title">print</span><span class="hljs-params">(<span class="hljs-string">'Class indicator: '</span>, product_code[<span class="hljs-number">0</span>])</span></span> <span class="hljs-function"><span class="hljs-title">print</span><span class="hljs-params">(<span class="hljs-string">'Model:'</span>, product_code[<span class="hljs-number">1</span>:])</span></span></pre></div><figure id="6a29"><img src="https://cdn-images-1.readmedium.com/v2/resize:fit:800/1*W5bLmLlyzDG1Xw6b6ZD0tQ.png"><figcaption></figcaption></figure><h1 id="c7e7">5. Enforcing Keyword Argument</h1><figure id="c4ac"><img src="https://cdn-images-1.readmedium.com/v2/resize:fit:800/1*VFncY3rfxgnl_no4EOMcPQ.jpeg"><figcaption>Image by <a href="https://pixabay.com/users/wokandapix-614097/?utm_source=link-attribution&amp;utm_medium=referral&amp;utm_campaign=image&amp;utm_content=2041816">Wokandapix</a> from <a href="https://pixabay.com/?utm_source=link-attribution&amp;utm_medium=referral&amp;utm_campaign=image&amp;utm_content=2041816">Pixabay</a></figcaption></figure><p id="5153">I won’t believe this is a frequent usage, because the requirement is not common. However, it is good to know that Python has such a feature. That is, we can put an asterisk in the parameter list in a function to force all the parameters to the right must be passed in with an explicit keyword.</p><p id="5cd2">For example, we can define a function as follows.</p><div id="9856"><pre><span class="hljs-keyword">def</span> <span class="hljs-title function_">my_func</span>(<span class="hljs-params">arg1, *, arg2</span>): <span class="hljs-built_in">print</span>(arg1) <span class="hljs-built_in">print</span>(arg2)</pre></div><p id="3fd6">Now, if we try to pass the two arguments, the error will be thrown.</p><div id="5646"><pre><span class="hljs-function"><span class="hljs-title">my_func</span><span class="hljs-params">(<span class="hljs-string">'a'</span>, <span class="hljs-string">'b'</span>)</span></span></pre></div><figure id="483c"><img src="https://cdn-images-1.readmedium.com/v2/resize:fit:800/1*Qh9JEI9EQJ1oOhxdyseZtA.png"><figcaption></figcaption></figure><p id="499d">To use this function, we have to explicitly specify the key of the parameter <code>arg2</code> because it is to the right of the asterisk.</p><div id="4155"><pre><span class="hljs-function"><span class="hljs-title">my_func</span><span class="hljs-params">(<span class="hljs-string">'a'</span>, arg2=<span class="hljs-string">'b'</span>)</span></span></pre></div><figure id="758b"><img src="https://cdn-images-1.readmedium.com/v2/resize:fit:800/1*K0gt3UbNj21MRreGDyuZTg.png"><figcaption></figcaption></figure><h1 id="b2e8">Summary</h1><figure id="5aa6"><img src="https://cdn-images-1.readmedium.com/v2/resize:fit:800/1*8bbfFMYlK8hLNhF2pO8OsA.jpeg"><figcaption>Image by <a href="https://pixabay.com/users/jplenio-7645255/?utm_source=link-attribution&amp;utm_medium=referral&amp;utm_campaign=image&amp;utm_content=3605547">jplenio</a> from <a href="https://pixabay.com/?utm_source=link-attribution&amp;utm_medium=referral&amp;utm_campaign=image&amp;utm_content=3605547">Pixabay</a></figcaption></figure><p id="cbb2">In this article, I have summarised all the 5 different usage patterns of asterisks in Python. It can be an operator or an indicator for passing variable-length arguments. It can also unpack lists, dictionaries or range objects, as well as pack them up.</p><div id="59d4" class="link-block"> <a href="https://medium.com/@qiuyujx/membership"> <div> <div> <h2>Join Medium with my referral link - Christopher Tao</h2> <div><h3>As a Medium member, a portion of your membership fee goes to writers you read, and you get full access to every story…</h3></div> <div><p>medium.com</p></div> </div> <div> <div style="background-image: url(https://miro.readmedium.com/v2/resize:fit:320/0*RqoTseLWLBP7HkKD)"></div> </div> </div> </a> </div><p id="e434"><b>If you feel my articles are helpful, please consider joining Medium Membership to support me and thousands of other writers! (Click the link above)</b></p></article></body>

Image by pasja1000 from Pixabay

5 Syntactic Applications Of Asterisks In Python, The Last One Is Surprising

The asterisks * contributed lots of syntactic sugar of Python

Many programming languages use asterisks “*” in many scenarios, so does Python. For example, one of the most common usages of asterisks in other programming languages is probably the memory pointers. This concept exists in many popular languages such as C++ and Objective-C.

However, Python doesn’t use memory pointers. Instead, there are much more cases that allow us to do more tricks using asterisks. This could either improve our code in terms of reliability or even bring some new features. That is the so-called “syntactic sugar”. In this article, I’ll list 5 tricks of the underscores. Hope they could help.

1. Operators

Image by NOST from Pixabay

Hmm, I bet everyone knows this. However, to ensure the completeness of this summary about the asterisks in Python, please allow me to present it here.

Using the asterisk sign as a multiply operator probably exists in all the programming languages.

Apart from that, Python introduces one more operator which is the power operator. a ** b will calculate the number a to the power of b. In some other programming languages, it could be a ^ b.

2. Passing Variable-Length Parameters

Image by 995645 from Pixabay

This is probably the most “Pythonic” usage of the asterisks. In Python, we can write a function that allows variable-length parameters.

For example, we can write such a function to sum all the numbers that passed in. To allow the parameter to be variable-length, we need to add an asterisk in front of the parameter name.

def sum_all(*numbers):
    print('numbers:', numbers)
    return sum(numbers)
sum_all(1, 2, 3, 4, 5)

Please be noted that I didn’t check the types of arguments if they are numbers. This function is only for demonstration purposes.

Python also allows passing key-value pairs in variable-length as parameters. We just need to put double asterisks in front of the parameter name as follows.

def give_me_dict(**my_dict):
    return my_dict
give_me_dict(name='Chris', age=33, gender='Male')

These two features give developers lots of flexibility during programming. If you want to know more about the variable-length parameters in Python, I have written another article for this topic for you to check out.

3. Unpacking List and Dictionary

Image by Peggy und Marco Lachmann-Anke from Pixabay

We usually need to use a for-loop to iterate a list or a dictionary when we want to do something to all their items. However, in some scenarios, we may not have to do so.

3.1 Unpacking List

Suppose we have a list of names as follows. Now we want to print all the names.

student_list = ['Alice', 'Bob', 'Chris']

We could use subscriptions to get them one by one, or a bit more clever, using a for-loop.

print(student_list[0], student_list[1], student_list[2])
# Or
for name in student_list:
    print(name)

There is another way that is even more clever, that is using an asterisk to unpack the list.

print(*student_list)

We can even unpack more than one list in one go.

print(*['Alice', 'Bob'], *['Chris'], 'David')

To combine multiple lists with some loose items, we can also use asterisks to unpack the lists.

[*['Alice', 'Bob'], *['Chris'], 'David']

This trick can also be used when we want to put multiple lists into a tuple or a set.

(*['Alice', 'Bob'], *['Chris'], 'David')
{*['Alice', 'Bob', 'Chris'], *['Chris'], 'David', 'Chris'}

Now, let’s consider a more advanced use case. We have got a 2-D list as follows. Each sub-list has two items, a name and an age. It is not easy to use so we want to transpose the 2-D list so that one list has all the names and the other one has all the ages.

my_list = [
    ['Alice', 31],
    ['Bob', 32],
    ['Chris', 33]
]

The easiest way to do this is to unpack the list in a zip() function.

for i in zip(*my_list):
    print(list(i))

This is equivalent to doing such.

for i in zip(['Alice', 31], ['Bob', 32], ['Chris', 33]):
    print(i)

If we still want a 2-D list, we can put the two sub-lists into a parent list using list comprehension.

[list(i) for i in zip(*my_list)]

If you are not quite familiar with the zip() function, please check out one of my previous articles that deep dive into this.

3.2 Unpacking Dictionary

Since Python 3.5, the asterisks can also unpack dictionaries, but we need to put double asterisks in front of the dictionary variable to unpack it.

One of the most common usages would be combining multiple dictionaries together. Suppose we have two dictionaries as follows to be combined, we can unpack them and put them inside another empty dictionary.

my_dict1 = {
    'name': 'Chris',
    'age': 33
}
my_dict2 = {
    'skill': 'Python'
}
my_dict = {**my_dict1, **my_dict2}

Another sample usage pattern will be the format string. Although I love the f-string syntax in Python, the format string still has some advantages. For example, it allows the parameterised string with parameter names.

"My name is {name}. I'm {age} years old and I can use {skill}".format(
    name='Chris',
    age=33,
    skill='Python'
)

In this case, we can unpack the previous dictionary and put it in the format string to pass the arguments.

"My name is {name}. I'm {age} years old and I can use {skill}".format(**my_dict)

This is very neat and clean. Also, we can even unpack multiple dictionaries into this.

"My name is {name}. I'm {age} years old and I can use {skill}".format(**my_dict1, **my_dict2)

3.3 Unpack Range

One of the usages that are not very common of using asterisks for unpacking is for a Python range. We usually use range() to tell a for-loop how many times it needs to be looped. We can also use it to generate a range of sequential numbers as follow.

list(range(10))

Syntactically, we can also use an asterisk to unpack the range object, though I don’t think there are any benefits in this case.

[*range(10)]

4. List Packing Up

Image by Kerstin Riemer from Pixabay

Yes, we can not only unpack lists using asterisks but also pack items up in some scenarios. For example, we can use the following syntax to use 3 variables for getting 3 items from a list respectively.

students = ['Alice', 'Bob', 'Chris']
my_classmate1, my_classmate2, me = students

Suppose in the above case, it doesn’t matter who are my classmates, we just want my name at the last and all the other names should remain in a list. In this case, we can use an asterisk to pack all the other items up.

students = ['Alice', 'Bob', 'Chris']
*other_students, me = students

You may know that the syntax is also applicable for a tuple. However, it needs to be noticed that using an asterisk for packing up the items will always return a list. In other words, it cannot be smart enough to return a tuple, though the original object is a tuple

students = ('Alice', 'Bob', 'Chris')
*other_students, me = students
print(me)
print(other_students)

Using this trick, we can also treat a string as a list of characters and get some particular ones with all the others packed up.

product_code = 'A320'
class_indicator, *model = product_code
print('Class indicator: ', class_indicator)
print('Model:', ''.join(model))

This is for demo purposes again, since I definitely believe using slicing is easier and more readable.

print('Class indicator: ', product_code[0])
print('Model:', product_code[1:])

5. Enforcing Keyword Argument

Image by Wokandapix from Pixabay

I won’t believe this is a frequent usage, because the requirement is not common. However, it is good to know that Python has such a feature. That is, we can put an asterisk in the parameter list in a function to force all the parameters to the right must be passed in with an explicit keyword.

For example, we can define a function as follows.

def my_func(arg1, *, arg2):
    print(arg1)
    print(arg2)

Now, if we try to pass the two arguments, the error will be thrown.

my_func('a', 'b')

To use this function, we have to explicitly specify the key of the parameter arg2 because it is to the right of the asterisk.

my_func('a', arg2='b')

Summary

Image by jplenio from Pixabay

In this article, I have summarised all the 5 different usage patterns of asterisks in Python. It can be an operator or an indicator for passing variable-length arguments. It can also unpack lists, dictionaries or range objects, as well as pack them up.

If you feel my articles are helpful, please consider joining Medium Membership to support me and thousands of other writers! (Click the link above)

Python
Programming
Artificial Intelligence
Technology
Data Science
Recommended from ReadMedium