Python Lists, Part 2

Python Lists, Part 2

For Loops

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'

map()

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

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:

  • list: a sequence collection
  • element: individual element in the list
  • expression: Action to apply on the element
  • condition: optional condition to apply to the element
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}]

List Comprehension with Conditional

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]

Set Comprehension

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'>

Dictionary Comprehension

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'>