Showing posts with label for loop. Show all posts
Showing posts with label for loop. Show all posts

Saturday, June 9, 2018

What is List Comprehension in Python?

Python supports list comrpehension. List Comprehension is a cool way to create a list (based on list construct). The examples are run on Python 3.7.

Here is an excerpt from Wikipedia:

"A list comprehension is a syntactic construct available in some programming languages for creating a list based on existing lists. It follows the form of the mathematical set-builder notation (set comprehension) as distinct from the use of map and filter functions."

You can create a list in Python using a for loop:


ListComprehension_0

Python supports List comprehension and you can create the same list as shown here:


ListComprehension_1

Don't you think this is far easier. It turns out it is more efficient as well since you avoid append().

You can do this kind of operation as well.


ListComprehension_2


You can filter the list in list comprehension also:

ListComprehension_3


Friday, June 1, 2018

How do you construct a Python dictionary?

Python dictionary has features common to JSON values.


Python dictionary has keys and associated with keys there are lists.
{key:[values],key[values]..}

Here is an example:

graph={"A":["C","B"],
       "B":["A","C"],
       "C":["A","B","D","E"],
       "D":["C","E"],
       "E":["C","D"]
      }


Defining a dictionary in Python.


Dict_0


In Python you can do the following to access keys and associated lists.

You can find the keys as show here:


Dict_1

You can gather all of the items in dictionary using the following:

Dict_2

You can list out the values only as shown here:


Dict_3

You can also access the lists by looping as in the following:


Dict_4


More in my next...