[[python_wiki:list_comprehensions]]

List Comprehensions

General Information

List comprehensions are a way to create lists based on lists.

They cut out a step in which you would create an intermediate list just to create a new list.

Checklist

  • Python 2 or 3

Usage

Using the code snippet.

chmod +x list-comp.py
./list-comp.py
 
# Example output
('The tuple is: ', ('centos', 'ubuntu', 'fedora', 'windows', 'arch', 'freebsd'))
('The nix os list is: ', ['centos', 'ubuntu', 'fedora', 'arch', 'freebsd'])

The Code

List Comprehension Syntax

new_list = [x for x in iterable if filter]


List Comprehension Example

list-comp.py
#!/usr/bin/python
 
# Tuple with a list of OS's
my_tuple = ('centos', 'ubuntu', 'fedora', 'windows', 'arch', 'freebsd')
 
# Create a new list based off of the tuple, exclude 'windows'
nix_os = [entry for entry in my_tuple if entry != 'windows']
 
print("The tuple is: ", my_tuple)
print("The nix os list is: ", nix_os)


The long way without list comprehensions of the above code is

#!/usr/bin/python
 
# Tuple with a list of OS's
my_tuple = ('centos', 'ubuntu', 'fedora', 'windows', 'arch', 'freebsd')
 
# Create a new list based off of the tuple, exclude 'windows'
# This time, do not use a list comprehension
nix_os = []
for entry in my_tuple:
  if entry != 'windows':
    nix_os.append(entry)
 
print("The tuple is: ", my_tuple)
print("The nix os list is: ", nix_os)

  • python_wiki/list_comprehensions.txt
  • Last modified: 2019/05/26 03:50
  • (external edit)