Python Lists, Part 2

Full Stack Data Dev.
Search for a command to run...

Full Stack Data Dev.
No comments yet. Be the first to comment.
Simple API Lockdown Introduction The previous article reviewed how to set and read environment variables. We'll use that knowledge and set up an API Key as an environment variable for authorization in a .NET Web API Project. Keys are a variable you w...

Creating and Reading ENVs

Introduction This article is the start of a series on how to build an API using the .NET Framework. I'm sticking with .NET 6, it is the latest Long-Term-Support (LTS) Version. I'll be using Visual Studio for Mac as my IDE. Before you start yelling, ...

Introduction This article will setup a basic Hello World FastAPI project running in Docker. The purpose is to start off small before starting on a full real world project. What and Why Docker is a containerization platform. Docker combines applica...

Introduction This article will continue our journey and connect a FastAPI project to a SQL Server database. We'll walk through a full CRUD (Create, Read, Update, Delete) example of saving data through our FastAPI project to a database. We'll work ...

As discussed in Part 1, a simple for loop will iterate through a sequential type value.
# Iterate through a list or string
name = "josh"
for n in name:
i
# OUTPUT:
# 'j'
# 'o'
# 's'
# 'h'
The map() feature offers an alternative to looping through a sequence while also applying a function on each traversed element.
The example below will traverse each element in the dictionary and activate the isActive field. We pass both the function and the array.
The map() function returns an object. To print the results, we convert the resulting object back to a list using list().
Lists are reference types so the original list is also updated.
users = [{"name": "Josh", "isActive": False}
, {"name": "Esmeralda", "isActive": False}
, {"name": "Daniel", "isActive": False}]
def activate_users(usr):
usr["isActive"] = True
return usr
updated_users = map(activate_users, users)
users_active = list(updated_users) # convert object to list
users_active
# OUTPUT:
# [{'name': 'Josh', 'isActive': True}
# , {'name': 'Esmeralda', 'isActive': True}
# , {'name': 'Daniel', 'isActive': True}]
List comprehensions offer a 'less lines of code' approach but can also get very complicated very quickly and also decrease readability.
The example below will apply the upper() function to each element in the names list.
List comprehensions return a list.
names = ["josh", "daniel", "esmeralda"]
names_upper = [name.upper() for name in names ]
names_upper
# OUTPUT:
# ['JOSH', 'DANIEL', 'ESMERALDA']
List comprehensions are composed of three main parts:
result_list = [expression for element in list]
result_list = [expression for element in list (optional) if condition]
Let's take a look at the map() example above and user a list comprehension to perform the same task. The output does not have to be converted to a list because a list comprehension's result is a list.
users = [{"name": "Josh", "isActive": False}
, {"name": "Esmeralda", "isActive": False}
, {"name": "Daniel", "isActive": False}]
def activate_users(usr):
usr["isActive"] = True
return usr
updated_users = [activate_users(usr) for usr in users]
updated_users
# OUTPUT:
# [{'name': 'Josh', 'isActive': True}
# , {'name': 'Esmeralda', 'isActive': True}
# , {'name': 'Daniel', 'isActive': True}]
grades = [90, 89, 75, 100, 85, 95, 70]
# Filter out only a grade that is equal to or more than 90
nineties = [grade for grade in grades if grade >= 90]
nineties
# OUTPUT:
# [90, 100, 95]
# Filter out only a grade that is equal to or more than 90
nineties = [grade if grade >= 90 else 0 for grade in grades]
nineties
# OUTPUT:
# [90, 0, 0, 100, 0, 95]
Very similar to list comprehensions but the resulting value is a set, meaning the result will not have duplicates. The format and components of set comprehensions are the same list comprehensions. Conditional statements are also optional to use in set comprehensions.
The example below removes the duplicate names from the set.
names = "josh esmeralda daniel esmeralda daniel josh".split()
names_set = { name for name in names }
names_set
# OUTPUT:
# {'daniel', 'esmeralda', 'josh'}
type(names_set)
# <class 'set'>
The last example will cover dictionary comprehensions that share similar properties and functionality as set and list comprehensions. The difference being that the result is a dictionary and a key index is required.
The example below will get a list of elements from the names dictionary.
For each key:value pair, the value is multiplied by 100 and a new dictionary is returned.
The original dictionary is not altered.
names = { "josh": .99, "daniel": .10, "esmeralda": .80 }
names_dict = { key:value*100 for (key, value) in names.items() }
names_dict
# OUTPUT:
# {'josh': 99.0, 'daniel': 10.0, 'esmeralda': 80.0}
type(names_dict)
# <class 'set'>