Comprehension lists

Comprehension lists allow you to create a new list of iterable objects. Basically, they contain the expression that must be executed for each element inside the loop that iterates over each element.

The basic syntax is:

new_list = [expression for_loop_one_or_more conditions]

List comprehensions can also be used to iterate over strings:

>>> protocolList = ["FTP", "HTTP", "SNMP", "SSH"]>>> protocolList_lower= [protocol.lower() for protocol in protocolList]>>> print(protocolList_lower) # Output: ['ftp', 'http', 'snmp', 'ssh']

Get Mastering Python for Networking and Security now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.