Created
March 17, 2019 08:53
-
-
Save ShyamaSankar/2b0de9a3bd67ea5ef2795dd2ef13e894 to your computer and use it in GitHub Desktop.
Nested for loop into a list comprehension
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
substrings_list = ["an", "the"] | |
strings_list = ["an apple", "the tree", "all trees", "an apple in the tree"] | |
# For loop to create a list of (substring, string) tuples from two lists. | |
# First is a list substrings and the second is a list of strings to be parsed. | |
tuple_list = [] | |
for string in strings_list: | |
for substring in substrings_list: | |
if substring in string: | |
tuple_list.append((substring, string)) | |
# Rewrite using list comprehension. | |
# Syntax: | |
# list_object = [expression_on_items for_item_in_iterable_1 | |
# for item_in_iterable_2 if_condition_on_items] | |
tuple_list = [(substring, string) for string in strings_list | |
for substring in substrings_list if substring in string] | |
print(tuple_list) | |
# Output: [('an', 'an apple'), ('the', 'the tree'), | |
# ('an', 'an apple in the tree'), ('the', 'an apple in the tree')] |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment