Learn Before
Concept

List Comprehension

List Comprehension in Python provides an easy way to initialize and populate a list in one line. It consists of an expression followed by a for clause and an ```if```` clause if necessary. For example, if you have a list of words and want to create a list of only those words which contain the letter i, you could use the example code below.

words = ["icky", "gross", "nasty", "illness", "disease"] newWords = [] for x in words: if "i" in x: newWords.append(x) print(newWords) #this will print: ['icky', 'illness', 'disease']

0

0

Updated 2021-05-18

Tags

Python Programming Language

Data Science