Tag Archives: Programming

Python Tutorial – List Comprehensions

PythonThis Python Tutorial post will introduce a very cool technique for Object Oriented guy like me: List Comprehensions. It provides way to create new lists while doing some operations to elements in the list.

List Comprehensions

Lets take a simple example how you would create a list of numbers in a range multiplied with two. Quite school example, but hang on.

This gets the job done. For object oriented guy this would be standard way to do this. There’s luckily shorter way to do same with comprehension.

Inside brackets first part is expression and after that there is for clause. Comprehension can has an optional part that can contain zero or more for and if clauses.

Here is an example of if clause in list comprehension.

Now comes the part that things get a bit ugly. Here are two versions of flattening loops.

I find the first version completely unusable because it looks very messy. I would gladly use latter version because you can understand it with one glimpse.

Conclusion

I started this post with saying that List Comprehensions are cool. They still are and somewhat usable way to shorten your code.
But.

List Comprehension comes with a price. They are almost always harder to read than their clearer versions. Think twice before writing something just for less lines of code.

Python Tutorial – Lists

PythonThis Python tutorial is about Lists – a workhorse of Python. Lists are like ArrayList in Java, it can hold any type of element and expands dynamically when needed.

Python Lists

No need to be super hero to figure out how Python lists are defined:

That’s enough. Put that to file and run it with Python.

Basic Usage

You can get individual value by referencing to it’s index in the List. Index starts from 0:

This will print first element from the list.

You can also have a negative index:

This will print last element of the list.
Slicing from a list is quite trivial – syntax is [from:to]:

Yes, you can use also a negative index in Python. If this confuses you, just open text file and experiment.

There’s also a shorthand for slicing:

Couldn’t be any easier.

Adding, removing, extending and some extra:

If you append a list, you will get a list inside a list! ([1,[2])

See if element is in the list:

Result is False.

You can also use list operators:

Conclusion

Lists truly are a workhorse of Python. They’re very easy to use and understand. Even for Java guy like me ! 😉

 

Python Tutorial – Dictionaries

PythonIn my previous blog post I talked about basics of Python. Now it’s time to discuss about one of the native datatypes of Python progamming language: Dictionaries.

Python Dictionaries

Dictionary is like Hashtable in Java: It’s constructed of keys and values that have one-to-one relationship. So, no duplicate keys and it’s unordered.

Here’s the simplest example of directory:

Looks familiar? Looks like JSON. You can nest same way than in JSON:

It’s not really JSON, but we can easily create one:

Previous example prints identically to standard print to dictionary:

{"username": "thatsme", "password": "letmein", "servers": {"host2": "192.168.1.67", "host1": "192.168.1.66"}}

You can access data from the dictionary:

This will print:

thatsme
192.168.1.66

Working with dictionaries

Assigning new value to a key is somewhat self explanatory:

Assigning new key-value pair is also easy:

Keys are case-sensitive. These are different entries:

Mixing datatypes is also allowed:

Deleting key from a dictionary and clearing it fully:

Get keys and values separately:

Conclusion

Python directories are very easy data structures to write and understand. This was just a small subset of methods and example usages of dictionaries. You can discover more by using autocomplete in your favourite IDE. Next blog post will introduce Lists.

Python Tutorial – The Basics

PythonI have wanted to try Python programming language. Now I had enough time to try it out. My goal was to learn why it is so popular and widely used. I started out with Django, but soon find out that it was too much. I needed to learn basics of Python first.

I found Dive Into Python web site which is tutorial for Python 2.x. There is already Python 3.x, but majority of programs and libraries work only with 2.x.

Python programming language

Python is interpreted, high-level and very readable programming language. It supports object-oriented, functional and imperative programming. It does not include curly brackets to indicate scope. Python uses indentation to separate code blocks. Language rejects Perl philosophy: “there is more than one way to do it” in favor of  “there should be one—and preferably only one—obvious way to do it”.

Python is dynamically typed and and strongly typed programming language.

Python implementations come with interactive REPL which is excellent way experiment language features. Just invoke python executable without any parameters and REPL will fire up itself. If you want more than instant executions you should try out some IDE. I used JetBrains PyCharm 30-day evaluation version.

First Python program

Python is very simple to learn and write. Here’s example of program:

That’s it. You can execute that in REPL or write snip to file that has a filename extension .py. Run by executing python hello.py or run inside PyCharm.

Defining a function

Defining a single function without any Class definitions is a no-brainer:

Every function starts with a keyword def  fallowed by name of the function and argument(s) in parentheses. Multiple arguments are separated with commas. Function definition ends with colon. In Python you don’t specify return type. Every function in Python returns a value and if there’s no return keyword defined, None is returned. None is Python’s null.

Remember to indent your code correctly!

Functions can define comments that begin and end with “””.  It’s sort of javadoc, but you can access it in run time using __doc__ built-in function.
Example above will print:

First line is printed by our newly defined function. Second line will print None because we did not return anything. Python will return None for us. Third line is the docstring of the function.

Conclusion

Python is very easy language to start programming. It holds very powerful ways to manipulate data which are essential for good programming language.

This was the first part of my Python tutorial. In the next part I will introduce Dictionaries, Lists and ways to manipulate them.