Body Age Buster

Helping you make the choices to live longer better — tips, plans, action and motivation.

Follow publication

Member-only story

Advanced Python List Methods and Techniques

Walter Adamson
Body Age Buster
Published in
5 min readNov 18, 2020

--

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.

Create an account to read the full story.

The author made this story available to Medium members only.
If you’re new to Medium, create a new account to read this story on us.

Or, continue in mobile web

Already have an account? Sign in

Body Age Buster
Body Age Buster

Published in Body Age Buster

Helping you make the choices to live longer better — tips, plans, action and motivation.

Walter Adamson
Walter Adamson

Written by Walter Adamson

Optimistically curious, 70+ trail runner; 2X cancer; diabetic; Click “FOLLOW” for living longer better tips | My Newsletter 👉 newsletter.walteradamson.com

No responses yet

Write a response