Learn List Comprehensions in Python Programming: List Comprehensions is a very powerful tool, which creates a new list based on another list, in a single, readable line. List comprehension is an elegant way to define and create lists based on existing lists. List comprehension is generally more compact and faster than normal functions and loops for creating list. However, we should avoid writing very long list comprehensions in one line to ensure that code is user-friendly.

For example, let’s say we need to create a list of integers which specify the length of each word in a certain sentence, but only if the word is not the word “the”.

sentence = "the quick brown fox jumps over the lazy dog"
words = sentence.split()
word_lengths = []
for word in words:
      if word != "the":
          word_lengths.append(len(word))
print(words)

Trinket.io on-line Python compiler

Using a list comprehension, we could simplify this process to this notation:

sentence = "the quick brown fox jumps over the lazy dog"
words = sentence.split()
word_lengths = [len(word) for word in words if word != "the"]
print(words)


Trinket.io on-line Python compiler

Exercise

Using a list comprehension, create a new list called “newlist” out of the list “numbers”, which contains only the positive numbers from the list, as integers.

# this is the answer code. Look below and see if you can complete the exercise on your own.
numbers = [34.6, -203.4, 44.9, 68.3, -12.2, 44.6, 12.7]
newlist = [int(x) for x in numbers if x > 0]
print(newlist)

Trinket.io on-line Python compiler

 


Related Videos:

MiltonMarketing.com Related Videos.

Related Posts:

Designing an app in Pseudo code

Methods of teaching programming

My little pony learning game in VB.NET

Learn Pandas Basics Python tabular data manipulation

Python Basic String Operations

Python Serialization (JSON)

Learn about Python Generators

Exception Handling in Python programming

Learn Python Lists

Learn about programming Loops in Python

How can Alice help teach OOP (Object Oriented Programming)?

Learn Modules and Packages in Python programming

Python Basic Operators

Introduction to JavaScript – Variables: String Interpolation

Introduction to JavaScript – Variables

Adding Python Comments

FAQs

Why do most sites use cookies?

How to make a go-back button with PHP code?

Learn about Python Sets (lists)

Introduction to JavaScript

Introduction to JavaScript – Variables: Review

Learn about Dictionaries datatype for Python

Introduction to JavaScript – Control Flow: if/else Statements

CSS, HTML, JAVASCRIPT, Online Compiler. Code on the go by replit.it

Google’s “Grasshopper” Mobile Game Teaches Adults How To Code In An Easy, Accessible Way — And It’s Free