Wednesday, 28 January 2015

Difference between write() and writelines()


Actually, you can use a single string together with write() and a sequence of strings together withwritelines().
write(arg) expects a string as argument and writes it to the file. If you provide a list of strings, it will raise an exception (btw, show errors to us!).
writelines(arg) expects an interable as argument (an iterable object can be a tuple, a list, or an iterator in the most general sense). Each item contained in the iterator is expected to be a string. A tuple of strings is what you provided, so things worked.
The nature of the string(s) does not matter to both of the functions, i.e. they just write to the file whatever you provide them. The interesting part is that writelines() does not add newline characters on its own, so the method name can actually be quite confusing. It actually behaves like an imaginary method called write_all_of_these_strings(sequence).
What follows is an idiomatic way in Python to write a list of strings to a file while keeping each string in its own line:
lines = ['line1', 'line2']
with open('filename.txt', 'w') as f:
    f.write('\n'.join(lines))
This takes care of closing the file for you. The construct '\n'.join(lines) concatenates (connects) the strings in the list lines with the character '\n'. It is more efficient than using +operator.
Starting from the same lines sequence, ending up with the same output, but using writelines():
lines = ['line1', 'line2']
with open('filename.txt', 'w') as f:
    f.writelines("%s\n" % l for l in lines)
This makes use of a generator expression and dynamically creates newline-terminated strings. writelines() iterates over this sequence of strings and .
Edit: Another point you should be aware of:
write() and readlines() existed before writelines() was introduced. writelines() was introduced later as a counterpart of readlines(), so that one could easily write the file content that was just read via readlines():
outfile.writelines(infile.readlines())
Really, this is the main reason why writelines has such a confusing name. Also, today, we do not really want to use this method anymore. readlines() reads the entire file to the memory of your machine before writelines() starts to write the data. First of all, this may waste time. Why not start writing parts of data while reading other parts? But, most importantly, this approach can be very memory consuming. In an extreme scenario, where the input file is larger than the memory of your machine, this approach won't even work. The solution to this problem is to use iterators only. A working example:
with open('inputfile') as infile:
    with open('outputfile') as outfile:
        for line in infile:
            outfile.write(line)
This reads the input file line by line. As soon as one line is read, this line is written to the output file. Schematically spoken, there always is only one single line in memory (compared to the entire file content being in memory in case of the readlines/writelines approach).

Friday, 16 January 2015

Slicing in python


Let 'a' is a list having element 1-10 as shown below

>>> a = range(1,11)
>>> a
[1, 2, 3, 4, 5, 6, 7, 8, 9, 10]

How exactly does slicing work is
a[Starting index : Ending index]
Which means it picks the list from the starting index to the last but one of the Ending index
it doesnt consider the element in the ending index position

>>> a[0:3]
[1, 2, 3]

We know when the index is negative number it reads the list from rightside
>>> a[-2]
9

If the Ending index is not provided then the whole list from the starting index is considered
>>> a[-2:]
[9, 10]
>>> a[0:]
[1, 2, 3, 4, 5, 6, 7, 8, 9, 10]

In the same way if starting index is not provided, the list is considered from 0 to the ending index
>>> a[:-1]
[1, 2, 3, 4, 5, 6, 7, 8, 9]

If the starting index is greater than the ending index, no list is printed
>>> a[-2:-5]
[]
>>> a[3:0]
[]

In order to print the whole list, simply give the colon without starting and ending index
>>> a[:]
[1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
>>> a[0:]
[1, 2, 3, 4, 5, 6, 7, 8, 9, 10]

Copying a list

In order to copy a list into a list but not referencing the list, this is how we do it

>>> b = a[:]

So now any operation performed on a doesnt reflect on b

>>> del(a[9])
>>> a
[1, 2, 3, 4, 5, 6, 7, 8, 9]
>>> b
[1, 2, 3, 4, 5, 6, 7, 8, 9, 10]

Basic List Operations


Range is a builtin function which given list as an output from the first parameter to the before numb of last parameter

List 'a' is assigned from 0-9

>>> a = range(0,10)
>>> a
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]

Len 

Len is a function used to return the length of the 'a' list
>>> len(a)
10

Concatenation in lists

When two lists are added then the list grows in size to a single list

>>> b = range(11,20)
>>> b
[11, 12, 13, 14, 15, 16, 17, 18, 19]

Here 'c' is an addition of two lists
>>> c = a+b
>>> c
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 11, 12, 13, 14, 15, 16, 17, 18, 19]

Equal operation in lists


In python when a list is assigned to another, it doesnt create a new list, instead it just creates a reference to the old one.
So any modification happening to the main list also effects in the assigned list
List 'c' is assigned to 'a'
>>> c=a
An element with index 9 has been deleted in the list 'a', and u can see it is not even seen in the list 'c'
>>> del(a[9])
>>> a
[0, 1, 2, 3, 4, 5, 6, 7, 8]
>>> c
[0, 1, 2, 3, 4, 5, 6, 7, 8]

Repetition in lists

To repeat the same values in the list 'n' number of times, simply say list*n
>>> d = range(0,4)
>>> d
[0, 1, 2, 3]
>>> d*3
[0, 1, 2, 3, 0, 1, 2, 3, 0, 1, 2, 3]

IN in lists

In is generally used to find whether the value is present in the list or not.
It simply returns true or false depending upon the presence of the element in list
>>> d
[0, 1, 2, 3]
>>> 4 in d
False
>>> 3 in d
True

IN used in For loop

For printing or using all the values in the list you can simply use the IN as shown below
>>> for i in d:
print i

0
1
2
3
>>> 

Lists in python


The list is a most versatile datatype available in Python which can be written as a list of comma-separated values (items) between square brackets. Good thing about a list is that items in a list need not all have the same type.
Creating a list is as simple as putting different comma-separated values between squere brackets. For example:
list1 = ['physics', 'chemistry', 1997, 2000]
list2 = [1, 2, 3, 4, 5 ]
list3 = ["a", "b", "c", "d"]
Like string indices, list indices start at 0, and lists can be sliced, concatenated and so on.

Accessing Values in Lists:

To access values in lists, use the square brackets for slicing along with the index or indices to obtain value available at that index. Following is a simple example:
list1= ['physics', 'chemistry', 1997, 2000]
list2 = [1, 2, 3, 4, 5, 6, 7 ]
print "list1[0]: ", list1[0] 

When the above code is executed, it produces the following result:
list1[0]:  physics

Updating Lists:

You can update single or multiple elements of lists by giving the slice on the left-hand side of the assignment operator, and you can add to elements in a list with the append() method. Following is a simple example:
list
= ['physics', 'chemistry', 1997, 2000]; print "Value available at index 2 : " print list[2] list[2] = 2001 print "New value available at index 2 : " print list[2]
Note: append() method is discussed in subsequent section.
When the above code is executed, it produces the following result:
Value available at index 2 :
1997
New value available at index 2 :
2001

Delete List Elements:

To remove a list element, you can use either the del statement if you know exactly which element(s) you are deleting or the remove() method if you do not know. Following is a simple example:
list1= ['physics', 'chemistry', 1997, 2000] 
print list1 del list1[2] 
print "After deleting value at index 2 : " print list1
When the above code is executed, it produces following result:
['physics', 'chemistry', 1997, 2000] After deleting value at index 2 : ['physics', 'chemistry', 2000]

Sunday, 4 January 2015

Difference between Split and Partition in python


Return Type

  • Split returns a list, where as Partition returns a tuple.
Size

  • The size of list returned by a Split functions depends on the seperator and the max split size which is again optional
  • The size of tuple returned by a partition is fixed and is always 3

Arguments

  • Split can work without any arguments, which by default takes spaces and '\n' as default seperator
  • For Partition an argument is compulsory, else returns an error