Python Tutorials

Overview

Python list comprehension offers a shorter syntax when you want to create a new list based on the values of an existing list.

Simple Loop Using List Comprehension

my_list = ["Ferrari", "Maserati", "Alfa Romeo"]
[print(x) for x in my_list]
Ferrari
Maserati
Alfa Romeo

Note

The return value is a new list, leaving the old list unchanged.

Syntax

[expression for item in iterable if condition == True]

Expression: The expression is the current item in the iteration, but it is also the outcome, which you can manipulate before it ends up like a list item in the new list

Example: Change to upper case.

my_list = ["Lamborghini", "Ferrari", "Maserati", "Alfa Romeo"]

new_list = [x.upper() for x in my_list]
print(new_list)
['LAMBORGHINI', 'FERRARI', 'MASERATI', 'ALFA ROMEO']

Example: Change all list items to new item.

my_list = ["Lamborghini", "Ferrari", "Maserati", "Alfa Romeo"]

new_list = ['Porsche' for x in my_list]
print(new_list)
['Porsche', 'Porsche', 'Porsche', 'Porsche']

Iterable: The iterable can be any iterable object, like a list, tuple, set etc.

Example:

new_list = [x for x in range(10)]

print(new_list)
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]

Note

Arrays count starting from zero NOT one. So item 1 is position [0], item 2 is position [1], and item 3 is position [2] … and so on.

Example: Accept only numbers lower than 8.

new_list = [x for x in range(10) if x < 8]

print(new_list)
[0, 1, 2, 3, 4, 5, 6, 7]

Condition: The condition is a filter that only accepts the items that are true to the condition.

Example: Only items with an “m” in them.

my_list = ["Lamborghini", "Ferrari", "Maserati", "Alfa Romeo"]
new_list = [x for x in my_list if "m" in x]

print(new_list)
['Lamborghini', 'Alfa Romeo']

Example: Only items the are NOT “Maserati”.

my_list = ["Lamborghini", "Ferrari", "Maserati", "Alfa Romeo"]
new_list = [x for x in my_list if x != "Maserati"]

print(new_list)
['Lamborghini', 'Ferrari', 'Alfa Romeo']

Python Notes:

  • The most recent major version of Python is Python 3; however, Python 2 is still in use and quite popular, although not being updated with anything other than security updates
  • Python uses new lines to complete a command, as opposed to other programming languages which often use semicolons or parentheses
  • Python relies on indentation, using whitespace to define scope, such as the scope of loops, functions, and classes; other programming languages often use curly-brackets for this purpose
  • Python string methods return new values, and DO NOT change the original string

We’d like to acknowledge that we learned a great deal of our coding from W3Schools and TutorialsPoint, borrowing heavily from their teaching process and excellent code examples. We highly recommend both sites to deepen your experience, and further your coding journey. We’re just hitting the basics here at 1SMARTchicken.