Python list comprehensions and generators

Python list comprehensions and generators

Both generate lists, but they are used differently, so I will summarize them lightly.

List comprehension

One of the common ways to write map-like methods. Python also has a map method, but list comprehensions are faster, so let's use this.

List comprehension and map

List comprehension

names = ['Alice', 'Bob', 'Carl', 'Dave']

[name[0] for name in names] # => ['A', 'B', 'C', 'D']

map method

names = ['Alice', 'Bob', 'Carl', 'Dave']

map(lambda name: name[0], names) # => ['A', 'B', 'C', 'D']

if list comprehension

It can be used when you want to create a new list of elements that meet the conditions from the list. It is possible to write multiple conditions by continuing if, and of course you can also write with and.

names = ['Alice', 'Bob', 'Carl', 'Dave']

[name for name in names if len(name) == 4] # => ['Carl', 'Dave']

[name for name in names if not len(name) == 4] # => ['Alice', 'Bob']

[name for name in words if not len(name) == 4 if len(name) < 5] # => ['Bob']

[name for name in words if not len(name) == 4 and len(name) < 5] # => ['Bob']

Multiple variables

You can create a new list from multiple lists at the same time by using zip.

namesA = ['Alice', 'Bob', 'Carl', 'Dave']
namesB = ['Peter', 'Micheal', 'John', 'Harry']

[" ".join([x, y]) for x, y in zip(namesA, namesB)]
# => ['Alice Peter', 'Bob Micheal', 'Carl John', 'Dave Harry']


Multiple loops can be expressed by overlapping for.

namesA = ['Alice', 'Bob', 'Carl', 'Dave']
namesB = ['Peter', 'Micheal', 'John', 'Harry']

[" ".join([x, y]) for x in namesA for y in namesB]
# => ['Alice Peter',
#     'Alice Micheal',
#     'Alice John',
#     'Bob Peter',
#     'Bob Micheal',
#     'Bob John',
#     'Carl Peter',
#     'Carl Micheal',
#     'Carl John',
#     'Dave Peter',
#     'Dave Micheal',
#     'Dave John']

generator

Generators can generate elements from defined expressions. You can retrieve the value from the generator with next.

g = (x ** 2 for x in range(5))

next(g) # => 0
next(g) # => 1
next(g) # => 4
next(g) # => 16
next(g) # StopIteration

You can use a generator to stop generating values when the conditions are met. There are other uses, though.


Bonus itertools

There is a Python module called itertools, which has nicely implemented methods to generate iterators.

For example, when you want to enumerate combinations

import itertools
itertools.combinations('ABCD', 2) # => (A,B) (A,C) (A,D) (B,C) (B,D) (C,D)

Note that this only creates an iterator, not a list.


This is where you can learn such a little notation while solving problems. Udacity Design of computer programming

Blogs doing (or trying to) machine learning with python Effort 1mm blog

Recommended Posts

Python list comprehensions and generators
Python iterators and generators
Python higher-order functions and comprehensions
[Python] list
Python tuple comprehensions and generator expressions
Difference between list () and [] in Python
Python basics: list
Python comprehension (list and generator expressions) [additional]
Python data structure and internal implementation ~ List ~
Difference between append and + = in Python list
list and sum
list and numpy
Python> Comprehension / Comprehension> List comprehension
[Python Iroha] Difference between List and Tuple
Python list manipulation
Python list comprehensions that are easy to forget
List of Python code to move and remember
[Python] A rough understanding of iterators, iterators, and generators
Sorted list in Python
Python Exercise 2 --List Comprehension
List of python modules
Python> list> extend () or + =
Python and numpy tips
[Python] pip and wheel
Batch design and python
Python list comprehension speed
Filter List in Python
Python packages and modules
Vue-Cli and Python integration
python unittest assertXXX list
Ruby, Python and map
Python3 List / dictionary memo
[Memo] Python3 list sort
OpenCV3 Python API list
Python error list (Japanese)
Python and Ruby split
Indent comprehensions in Python
List find in Python
Python3, venv and Ansible
Python asyncio and ContextVar
Python exception class list
Initialize list with python
Mayungo's Python Learning Note: List of stories and links
Implemented List and Bool in Python and SQLite3 (personal note)
List of Python libraries for data scientists and data engineers
Writing using lambda expressions and filter functions and writing using list comprehensions
[Python] How to sort dict in list and instance in list
Generate Fibonacci numbers with Python closures, iterators, and generators
EP 7 Use List Comprehensions Instead of map and filter
Programming with Python and Tkinter
Python hand play (two-dimensional list)
Encryption and decryption with Python
Let's review the language specifications around Python iterators and generators
Python: Class and instance variables
3-3, Python strings and character codes
Python list, for statement, dictionary
Python 2 series and 3 series (Anaconda edition)
Python and hardware-Using RS232C with Python-
Summary of Python3 list operations
Python on Ruby and angry Ruby on Python
Python real division (/) and integer division (//)