10 Python One-Liners for Lists

Shen Ge
CodeX
Published in
4 min readDec 14, 2021

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)
# 125
total = 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]

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.

cost.sort()
print(cost)
#[23, 24, 26, 29, 35, 41]
cost.sort(reverse=True)
print(cost)
#[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.

cost.pop(0)
# 23
print(cost)
# [24, 26, 29, 41, 29, 35]
cost.pop(-1)
# 35
print(cost)
# [24, 26, 29, 41, 29]

Shen Ge
CodeX
Writer for

Aerospace engineer who enjoys Python, math, physics, space and poetry. Become a member and read all my work: https://medium.com/@shenge86/membership