[009] Introduction to Python Basics: Common List Patterns, List unpacking

Koay Yong Cett
4 min readJun 28, 2020
Photo by Aaron Burden on Unsplash

Let’s talk about some useful tricks with lists that we will see a lot in Python code.

  • Well, one of it that we already review about it which is the length function. We will be using this a lot that is to figure out the length in our case.
  • Here we get 7 in the result.

Beside the reverse method for the list, we can also do the list slicing for reversing the list.

  • Is this what you expected to get? Think about it.
  • Analyze the code line by line and this will allow you to understand it.
  • For the print basket([::-1]), we will print the reverse copy of the reverse sorted basket list.
  • While for the print basket, we will print the reverse sort order of the list.

Another useful thing that we will see a lot is range.

  • This allow us to generate a list very quickly like 1 to 100.
  • If I wrap this in a list which will create a new list for us. Here, we get a range of 1 to 99 (remember start at 1 and stop before 100).
  • We may also get a list from 0 to 99. This is definitely will allow us to generate a list really quickly especially a numbered list.

Another common patterns that we will see a lot that is join and what is it?

  • It is actually something that work on list which is a string method.
  • This line of code yielded a “!” and seems like the dot join creates a new item for us.
  • Let’s assign the dot join to new sentence and print the result out. Now, we get the sentence.
  • Now, we add a space in the sentence then we will get the list join together with an empty space.
  • This is a shorthand way of doing this and yielded the same result as the previous one.

List unpacking is a very nice feature to be learn.

  • We are able to print the list like this way where we assign each item of the list to one variable.
  • We may also have the same result when we do this.
  • This is where the list unpacking gets really useful. We can actually extend our list to include all the way till nine. What if we wanted to unpack one, two and three but keep everything else in the list.
  • Can we still do that? Yes, we can do this with list unpacking.We are able to do this by adding *other in the code.
  • When we add d, then print the d will get the very last item which is 9. This is very neat which is useful in unpack the list and change the list.

Thanks for reading my stories 😃

--

--

Koay Yong Cett

A Bachelor CS student with major in Network Security (UniSZa). Every stories I shared is based on my personal opinion. Thanks you. Having my Internship now.