Thursday, November 23, 2017

Python libraries and Data Structures

Python Data Structures
Following are some data structures, which are used in Python. You should be familiar with them in order to use them.

Lists – Lists are one of the most versatile data structure in Python. A list can simply be defined by writing a list of comma separated values in square brackets. Lists might contain items of different types, but usually the items all have the same type. Python lists are mutable and individual elements of a list can be changed.
Here is a quick example to define a list and then access it:
country = ["Brazil", "Russia", "India", "China", "South Africa"]
Individual elements of a list can be accessed by writing the index number in square bracket. Keep in mind that the first index of a list is 0 and not 1.
print(country[1])
#returns – Russia
A range of a script can be accessed by providing first index number and last index number.
print(country[1:3])
#returns - ['Russia', 'India']
A negative index accesses the elements of a list from end.
print(country[-2])
#returns - 'China'
A few common methods applicable to the list include: append(), extend(), insert(), remove(), count(), sort(), reverse().

Strings – Strings can simply be defined by use of single ( ‘ ), double ( ” ) or triple ( ”’ ) inverted commas. Strings enclosed in tripe quotes ( ”’ ) can span over multiple lines and are used frequently in docstrings (Python’s way of documenting functions). \ is used as an escape character. Please note that Python strings are immutable, so you cannot change part of strings.
greeting = 'Hello'
print(greeting[1])             # Returns the char of the index value 1. e
print(len(greeting))           # Prints the length of string. 5
print(greeting +' ' +'World')  # Prints Hello World.
 
Raw string can be used to pass on string as is. Python interpreter does not alter the string if you specify a string to be raw. Raw string can be defined by adding r to the string.
string = r'\n is a new line char by default.'
print(string)          # Returns - \n is a new line char by default.
Python strings are immutable and hence can't be changed.
greeting[1:] = 'i'     # Trying to change Hello to Hi. This will result an error.
 
Dictionary – Dictionary is an unordered set of key: value pairs, with the requirement that the keys are unique (within one dictionary).
Following is a simple example –
dict = {'Name': 'Zara', 'Age': 7, 'Class': 'First'}
print "dict['Name']: ", dict['Name']
print "dict['Age']: ", dict['Age']
When the above code is executed, it produces the following result –
dict['Name']:  Zara
dict['Age']:  7


Monday, November 20, 2017

Lists and Tuples in Python

Lists are what they seem - a list of values. Each one of them is numbered, starting from zero - the first one is numbered zero, the second 1, the third 2, etc. You can remove values from the list, and add new values to the end. Example: Your many cats' names.
Tuples are just like lists, but you can't change their values. The values that you give it first up, are the values that you are stuck with for the rest of the program. Again, each value is numbered starting from zero, for easy reference. Example: the names of the months of the year.

Tuples
Tuples are pretty easy to make. You give your tuple a name, then after that the list of values it will carry. For example, the months of the year:
months = ('January','February','March','April','May','June','July','August','September','October','November','December')

Python then organises those values in a handy, numbered index - starting from zero, in the order that you entered them in. It would be organised like this:

Index
Value
0
January
1
February
2
March
3
April
4
May
5
June
6
July
7
August
8
September
9
October
10
November
11
December

Lists
Lists are very similar to tuples. Lists are modifiable (or 'mutable'), so their values can be changed. Most of the time we use lists, not tuples, because we want to easily change the values of things if we need to.
Lists are defined very similarly to tuples. Say you have FIVE cats, called Tom, Snappy, Kitty, Jessie and Chester. To put them in a list, you would do this:
cats = ['Tom', 'Snappy', 'Kitty', 'Jessie', 'Chester']
You recall values from lists exactly the same as you do with tuples. For example, to print the name of your 3rd cat you would do this:
print(cats[2])
You can also recall a range of examples, like above, for example - cats[0:2] would recall your 1st and 2nd cats.
Where lists come into their own is how they can be modified. To add a value to a list, you use the 'append()' function. Let's say you got a new cat called Catherine. To add her to the list you'd do this:
cats.append('Catherine')


Tuesday, November 14, 2017

List Comprehensions in Python

List comprehensions provide a concise way to create lists. It consists of brackets containing an expression followed by a for clause, then zero or more for or if clauses. The expressions can be anything, meaning you can put in all kinds of objects in lists.

The result will be a new list resulting from evaluating the expression in the context of the for and if clauses which follow it. 

The list comprehension always returns a result list. 

If you used to do it like this:
new_list = []
for i in old_list:
    if filter(i):
        new_list.append(expressions(i))

You can obtain the same thing using list comprehension:
new_list = [expression(i) for i in old_list if filter(i)]

Examples

x = [i for i in range(10)]
print x
# This will give the output:
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]

For the next example, assume we want to create a list of squares.

# You can either use loops:
squares = []

for x in range(10):
    squares.append(x**2)
 
print squares
[0, 1, 4, 9, 16, 25, 36, 49, 64, 81]

# Or you can use list comprehensions to get the same result:
squares = [x**2 for x in range(10)]

# print squares
[0, 1, 4, 9, 16, 25, 36, 49, 64, 81]