List Comprehension is a compact way to process all or part of the elements in a sequence (or iterable objects) and return a list with the results.
Common applications are to make new lists where each element is the result of some operations applied to each member of another sequence or iterable, or to create a subsequence of those elements that satisfy a certain condition. --List Comprehensions
List Comprehension is an alternative to the Map-Filter-Reduce Functions that implement Functional Programming style.
Using List Comprehension technique, the following code example opens a text file i.e. the VADER lexicon data and manipulate them as an iterable object.
with open("vader.txt", 'r') as f:
#using list comprehension
listLexicon = [row.rstrip('\n') for row in f]
print(listLexicon[0].split("\t")[0])
#using list comprehension
print([item.split("\t")[0] for item in listLexicon][0:3])
#using list comprehension
print([item.split("\t")[0] for item in listLexicon if ")" in item])
0 Comments