Created
May 7, 2012 04:50
-
-
Save johnpneumann/2625980 to your computer and use it in GitHub Desktop.
List Comprehensions and Lambdas
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
""" | |
Create a new list based upon whether or not the object in the list is a string or not (by utilizing isinstance - if we wanted to only find integers we'd change str to int). | |
""" | |
# Lame | |
my_list = ['a', 'b', 'c', '1', 1, 2, 'd', 'e', '2'] | |
new_list = [] | |
for object in my_list: | |
if isinstance(object, str): | |
new_list.append(object) | |
# Awesome | |
my_list = = ['a', 'b', 'c', '1', 1, 2, 'd', 'e', '2'] | |
new_list = [object for object in my_list if isinstance(object, str)] | |
""" | |
Here we determine whether or not a list has at least 1 object in it or not. If it is empty the result is True and if it isn't it returns False. Simple. | |
""" | |
# Lame | |
my_list = [] # an empty list | |
def is_empty(x): | |
if len(a) < 1: | |
return True | |
else: | |
return False | |
result = is_empty(my_list) | |
# Awesome | |
my_list = [] # an empty list | |
is_empty = lambda x: True if len(x) < 1 else False | |
result = is_empty(my_list) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment