Book Image

Python Fundamentals

By : Ryan Marvin, Mark Nganga, Amos Omondi
Book Image

Python Fundamentals

By: Ryan Marvin, Mark Nganga, Amos Omondi

Overview of this book

After a brief history of Python and key differences between Python 2 and Python 3, you'll understand how Python has been used in applications such as YouTube and Google App Engine. As you work with the language, you'll learn about control statements, delve into controlling program flow and gradually work on more structured programs via functions. As you settle into the Python ecosystem, you'll learn about data structures and study ways to correctly store and represent information. By working through specific examples, you'll learn how Python implements object-oriented programming (OOP) concepts of abstraction, encapsulation of data, inheritance, and polymorphism. You'll be given an overview of how imports, modules, and packages work in Python, how you can handle errors to prevent apps from crashing, as well as file manipulation. By the end of this book, you'll have built up an impressive portfolio of projects and armed yourself with the skills you need to tackle Python projects in the real world.
Table of Contents (12 chapters)
Python Fundamentals
Preface

List Comprehensions


List comprehensions are a feature of Python that give us a clean, concise way to create lists.

A common use case would be when you need to create a list where each element is the result of some operations applied to each member of another sequence or iterable object.

The syntax for a list comprehension is pretty similar to creating a list the traditional way. It consists of square brackets [] containing an expression followed by a for clause, then zero or more if clauses.

Let's go back to the example we looked at previously, where we needed to calculate the squares of numbers. To calculate the squares of all numbers from one to ten using a for loop, we could do the following:

Python 3.6.1 (default, Dec 2015, 13:05:11)
[GCC 4.8.2] on linux
   for num in range(1,11): 
     print(num**2)
   
1
4
9
16
25
36
49
64
81
100

The same can be achieved by using list comprehensions, as follows:

Python 3.6.1 (default, Dec 2015, 13:05:11)
[GCC 4.8.2] on linux
   squares = [num**2 for num...