Differences
This shows you the differences between two versions of the page.
Next revision | Previous revision | ||
python_wiki:list_comprehensions [2018/08/03 00:46] billdozor created |
python_wiki:list_comprehensions [2018/08/03 00:58] billdozor [Usage] |
||
---|---|---|---|
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 |
+ | ./ | ||
+ | |||
+ | # Example output | ||
+ | ('The tuple is: ', (' | ||
+ | ('The nix os list is: ', [' | ||
</ | </ | ||
Line 25: | Line 28: | ||
====== The Code ====== | ====== The Code ====== | ||
- | <code python | + | **List Comprehension Syntax** |
- | Program | + | <code python> |
+ | new_list = [x for x in iterable if filter] | ||
+ | </ | ||
+ | |||
+ | \\ | ||
+ | **List Comprehension Example** | ||
+ | <code python list-comp.py> | ||
+ | # | ||
+ | |||
+ | # Tuple with a list of OS's | ||
+ | my_tuple = (' | ||
+ | |||
+ | # Create a new list based off of the tuple, exclude ' | ||
+ | nix_os = [entry for entry in my_tuple if entry != ' | ||
+ | |||
+ | print(" | ||
+ | print(" | ||
+ | </code> | ||
+ | |||
+ | \\ | ||
+ | The long way **without list comprehensions** of the above code is | ||
+ | <code python> | ||
+ | # | ||
+ | |||
+ | # Tuple with a list of OS's | ||
+ | my_tuple = (' | ||
+ | |||
+ | # Create a new list based off of the tuple, exclude ' | ||
+ | # This time, do not use a list comprehension | ||
+ | nix_os = [] | ||
+ | for entry in my_tuple: | ||
+ | if entry != ' | ||
+ | nix_os.append(entry) | ||
+ | |||
+ | print(" | ||
+ | print(" | ||
</ | </ | ||
---- | ---- | ||