python_wiki:list_comprehensions

Differences

This shows you the differences between two versions of the page.

Link to this comparison view

Next revision
Previous revision
python_wiki:list_comprehensions [2018/08/03 00:46]
billdozor created
python_wiki:list_comprehensions [2019/05/25 23:50] (current)
Line 14: Line 14:
 ====== Usage ====== ====== Usage ======
  
-FIXME -> Fill out list comprehension example and code+Using the code snippet
- +
-Instructions here.+
 <code bash> <code bash>
-Execution code here+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'])
 </code> </code>
  
Line 25: Line 28:
 ====== The Code ====== ====== The Code ======
  
-<code python program-name.py> +**List Comprehension Syntax** 
-Program code here+<code python
 +new_list = [x for x in iterable if filter] 
 +</code> 
 + 
 +\\ 
 +**List Comprehension Example** 
 +<code python 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) 
 +</code
 + 
 +\\ 
 +The long way **without list comprehensions** of the above code is 
 +<code python> 
 +#!/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)
 </code> </code>
  
 ---- ----
  
  • python_wiki/list_comprehensions.1533271573.txt.gz
  • Last modified: 2019/05/25 23:50
  • (external edit)