List is probably the most commonly used data type in Python. We deal with it all the time in our projects. But sometimes we often just wanted to get things done and forgot to think a bit deeper to find if there are better ways to implement it.
For me, sometimes I find myself having to search the internet for some simple problems like "how to append a list to a list" or "how to reverse items in a list". After I found the solutions on the internet, I often realized that, wow Python is so smart and powerful, it almost always have some concise, intuitive built-in functions for what I need. Then, I thought why don't I try to remember some of the keys functions or techniques that I use regularly. That will save me lots of time and make me feel good about my programming skills!. I know some may not agree with this, but that's okay, I don't want to rely on searching Google on everything!
So, today I will put together the most important notes about Python List that I have collected over the time I worked on Python.
First of all, let's define a list.
Probably the most commonly used method of List is 'append()' method to add an item at the end of the list. However, I find a function that sometimes got under-used that is 'extent()' function to add a list to another list. I once run into a code written by someone that do a for loop to add items of a list to another list!
And, actually we can do the things above in a very much simpler way without remembering about the 'append()' or 'extend()' functions at all. We can just use math operator to add more items to a list.
To sort items in a list, we can use 'sort()' method. This method will sort and change order of items in the list.
We can also using the built-in global 'sorted()' function. But note that this sorted() function sort and return the sorted list without changing the original list. This can be very useful sometime when we still want to keep the original one.
Sometimes, we need to reverse the order of items in a list, we can use 'reverse()' method to do that.
Those are some most commonly used techniques with Python List that I encountered. What are yours?
Happy Pythoning!
Comments