Member-only story
Advanced Python List Methods and Techniques
One of the most powerful data structures in Python is the list; here are some more advanced list uses

One of the most powerful data structures in Python is the list. I didn’t really believe that until I started working through the documentation and realized just how much work had been put into building the list data structure.
Python lists natively support being utilized as queues, stacks, and arrays. This is why, to use Python like a pro, it is important to have a good understanding of lists.
In this article, we will cover list comprehensions, the zip
method, and the sort
method.
List Comprehensions
Comprehensions are an advanced feature of Python lists that can help make code cleaner and easier to read.
A composition is simply a way of performing a series of operations on a list using a single line. Comprehensions are denoted typically by the use of a for
statement inside brackets.
Here is a template for list comprehensions:
newList = [returned_value for item in list condition_logic ]
Pulling out specific elements
List comprehensions can be used to pull out certain elements that meet specific criteria. In the following example, we use a comprehension to pull out all the even numbers from a list.
# Create a list of numbers from 0 - 49
numRange = range(0,50)# Pull out all the numbers that are even
evenNums = [num for num in numRange if num % 2 == 0 ]
In the above example, reading from left to right we are creating a new list with the num
that is returned from the for loop where the remainder (%
modulo) of the num
divided by two is equal to zero.
This is a common use case where all the even numbers need to be pulled from a list.
Perform an operation on elements
List comprehensions can be used to perform operations on elements in a list. The following example shows how all the elements of a list could be squared.