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 cost=[23,24,26,29,41,29,35]
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])
print(total)
# 87
More generally, we can use slicing to create new lists based off of our original.
cost_every_other = cost[::2]
print(cost_every_other)
# [23, 26, 41, 35]cost_every_other_skippingfirst = cost[1::2]
print(cost_every_other_skippingfirst)
# [24, 29, 29]