Lists are one of the four built-in data structures (lists, tuples, sets and dictionaries) for holding a collection of objects in Python. Since we use lists so frequently, knowing a few one-liner code to work with lists can be greatly helpful. Here are ten of them which you may find yourself frequently using.
In all these examples, we will use the list
Note for adding or removing elements in a list, the one-liners that use the list methods and statements such as
del directly changes the original list whereas external functions such as
sum() applied to the list does not.
1. Sum every nth value in a list
You may know that to find the sum of a list is to use the
sum() function but how do you do it for every other item? We use slicing here. First index is start (inclusive) and the last index is stop (exclusive). The third parameter is the step which defines the step size. If the third parameter is not given, it is assumed to be
total = sum(cost[::2])print(total)
# 125total = sum(cost[::3])
More generally, we can use slicing to create new lists based off of our original.
cost_every_other = cost[::2]
# [23, 26, 41, 35]cost_every_other_skippingfirst = cost[1::2]
# [24, 29, 29]
2. Sort a list ascending and descending
All lists come with a method called
sort() which sorts the list from smallest to largest. To sort it in descending, simply use the reverse=True argument.
#[23, 24, 26, 29, 35, 41]
#[41, 35, 29, 26, 24, 23]
3. Removes element at specified position
We can remove elements from a list from any position by using the
pop() method. Note that it returns the element.
Alternatively, we can use the
del statement. This differs from the
pop() method in that it does not return a value. It can also be used to remove slices from a list or the entire list.
# [24, 26, 29, 41, 29, 35]
# [24, 26, 29, 41, 29]