In [ ]:
# lists
# A linear representation of data is called list.
# a list could be homogenous or hetrogenous.
# array vs list
# array is multi dimension representation of data - numpy
# http://scipy.org/

In [5]:
my_fruits = ['apple','banana','custard','dates']
my_empty = []
my_empty1 = list()

In [6]:
print my_fruits,type(my_fruits)
print my_empty,type(my_empty)
print my_empty1,type(my_empty1)


['apple', 'banana', 'custard', 'dates'] <type 'list'>
[] <type 'list'>
[] <type 'list'>

In [ ]:
# lists are indexed values
# my_fruits = ['apple','banana','custard','dates']
#                0         1         2       3      # +ve index or left to right.
#               -4        -3         -2      -1     # -ve index or right to left

In [7]:
print my_fruits[0]


apple

In [8]:
print my_fruits[-1]


dates

In [ ]:
# slicing

In [10]:
#for(i=0;i<=3;i+2)
print my_fruits[0:3] # zero till three
print my_fruits[0:3:2]


['apple', 'banana', 'custard']
['apple', 'custard']

In [12]:
# you can modify the list
my_string="python"
print my_string[0]
my_string[0]="P"


p
---------------------------------------------------------------------------
TypeError                                 Traceback (most recent call last)
<ipython-input-12-15b0c0f30618> in <module>()
      2 my_string="python"
      3 print my_string[0]
----> 4 my_string[0]="P"

TypeError: 'str' object does not support item assignment

In [14]:
print my_fruits[0]
my_fruits[0]='Apple'


apple

In [15]:
print my_fruits


['Apple', 'banana', 'custard', 'dates']

In [32]:
# list is an iterable
for value in my_fruits:
    print value


Apple
banana
custard
dates

In [19]:
# in operator
print my_fruits
print 'Apple' in my_fruits
print 'apple' in my_fruits
print 'p' in 'python'


['Apple', 'banana', 'custard', 'dates']
True
False
True

In [21]:
# converting a list to a string and vice-versa.

# convert a string to a list.
my_string="python"
Lmy_string=list(my_string)
print Lmy_string
Lmy_string[0]='T'
print Lmy_string


['p', 'y', 't', 'h', 'o', 'n']
['T', 'y', 't', 'h', 'o', 'n']

In [30]:
# convert a list to a string.
delimiter=""
print help(delimiter.join)


Help on built-in function join:

join(...)
    S.join(iterable) -> string
    
    Return a string which is the concatenation of the strings in the
    iterable.  The separator between elements is S.

None

In [31]:
print delimiter.join(Lmy_string)
new_string = delimiter.join(Lmy_string)
print new_string


Tython
Tython

In [33]:
# sentence
# convert a string to a list.
my_sentence = "today is friday"
Lmy_sentence = list(my_sentence)
print Lmy_sentence


['t', 'o', 'd', 'a', 'y', ' ', 'i', 's', ' ', 'f', 'r', 'i', 'd', 'a', 'y']

In [41]:
my_sentence = "today is friday"
print help(my_string.split)
my_email="tuxfux"
print my_email.split()


Help on built-in function split:

split(...)
    S.split([sep [,maxsplit]]) -> list of strings
    
    Return a list of the words in the string S, using sep as the
    delimiter string.  If maxsplit is given, at most maxsplit
    splits are done. If sep is not specified or is None, any
    whitespace string is a separator and empty strings are removed
    from the result.

None
['tuxfux']

In [35]:
Lmy_sentence = my_sentence.split()

In [38]:
print Lmy_sentence
Lmy_sentence[2]='Thursday'
print Lmy_sentence


['today', 'is', 'friday']
['today', 'is', 'Thursday']

In [48]:
# converting a list to a string.
#azhar=" "
#azhar.join(Lmy_sentence)
new_sentence=" ".join(Lmy_sentence)
print Lmy_sentence
print my_sentence
print new_sentence


['today', 'is', 'Thursday']
today is friday
today is Thursday

In [49]:
# functions
print my_fruits


['Apple', 'banana', 'custard', 'dates']

In [50]:
print dir(my_fruits)


['__add__', '__class__', '__contains__', '__delattr__', '__delitem__', '__delslice__', '__doc__', '__eq__', '__format__', '__ge__', '__getattribute__', '__getitem__', '__getslice__', '__gt__', '__hash__', '__iadd__', '__imul__', '__init__', '__iter__', '__le__', '__len__', '__lt__', '__mul__', '__ne__', '__new__', '__reduce__', '__reduce_ex__', '__repr__', '__reversed__', '__rmul__', '__setattr__', '__setitem__', '__setslice__', '__sizeof__', '__str__', '__subclasshook__', 'append', 'count', 'extend', 'index', 'insert', 'pop', 'remove', 'reverse', 'sort']

In [51]:
# append
print help(my_fruits.append)


Help on built-in function append:

append(...)
    L.append(object) -- append object to end

None

In [52]:
my_fruits.append('grapes')
print my_fruits


['Apple', 'banana', 'custard', 'dates', 'grapes']

In [53]:
# extend
print help(my_fruits.extend)


Help on built-in function extend:

extend(...)
    L.extend(iterable) -- extend list by appending elements from the iterable

None

In [54]:
my_fruits.extend(['jackfruits','kiwi','leechi'])
print my_fruits


['Apple', 'banana', 'custard', 'dates', 'grapes', 'jackfruits', 'kiwi', 'leechi']

In [55]:
# insert
print help(my_fruits.insert)


Help on built-in function insert:

insert(...)
    L.insert(index, object) -- insert object before index

None

In [56]:
my_fruits.insert(3,'mango')
print my_fruits


['Apple', 'banana', 'custard', 'mango', 'dates', 'grapes', 'jackfruits', 'kiwi', 'leechi']

In [57]:
# index
print help(my_fruits.index)


Help on built-in function index:

index(...)
    L.index(value, [start, [stop]]) -> integer -- return first index of value.
    Raises ValueError if the value is not present.

None

In [58]:
print my_fruits.index('mango')


3

In [61]:
my_fruits = ['Apple', 'banana', 'custard', 'mango', 'dates', 'grapes', 'mango','jackfruits', 'kiwi', 'leechi']
print my_fruits.index('mango')
print my_fruits.index('mango',4)


3
6

In [62]:
#count
print help(my_fruits.count)


Help on built-in function count:

count(...)
    L.count(value) -> integer -- return number of occurrences of value

None

In [64]:
print my_fruits.count('mango')
print my_fruits.count('gauva')


2
0

In [68]:
# pop
print help(my_fruits.pop)
print my_fruits.pop()
print my_fruits
print my_fruits.pop(1)
print my_fruits


Help on built-in function pop:

pop(...)
    L.pop([index]) -> item -- remove and return item at index (default last).
    Raises IndexError if list is empty or index is out of range.

None
jackfruits
['Apple', 'custard', 'mango', 'dates', 'grapes', 'mango']
custard
['Apple', 'mango', 'dates', 'grapes', 'mango']

In [69]:
print my_fruits.pop(10)


---------------------------------------------------------------------------
IndexError                                Traceback (most recent call last)
<ipython-input-69-caee7eda01fa> in <module>()
----> 1 print my_fruits.pop(10)

IndexError: pop index out of range

In [71]:
# remove
print help(my_fruits.remove)
print my_fruits.remove('mango')
print my_fruits


Help on built-in function remove:

remove(...)
    L.remove(value) -- remove first occurrence of value.
    Raises ValueError if the value is not present.

None
None
['Apple', 'dates', 'grapes', 'mango']

In [72]:
print my_fruits.remove('gauva')


---------------------------------------------------------------------------
ValueError                                Traceback (most recent call last)
<ipython-input-72-6a5a8a889a13> in <module>()
----> 1 print my_fruits.remove('gauva')

ValueError: list.remove(x): x not in list

In [76]:
# reverse
print help(my_fruits.reverse)
print my_fruits.reverse()
print my_fruits


Help on built-in function reverse:

reverse(...)
    L.reverse() -- reverse *IN PLACE*

None
None
['mango', 'grapes', 'dates', 'Apple']

In [77]:
# sort
print help(my_fruits.sort)


Help on built-in function sort:

sort(...)
    L.sort(cmp=None, key=None, reverse=False) -- stable sort *IN PLACE*;
    cmp(x, y) -> -1, 0, 1

None

In [80]:
# reverse=False =>ascending
# reverse=True =>descending
print my_fruits.sort()


None

In [81]:
print my_fruits


['Apple', 'dates', 'grapes', 'mango']

In [2]:
# task1

days = ['yesterday','today','tomorrow','dayafter']

In [ ]:
# output 1:
# yesterday 9
# today     5
# tomorrow  8
# dayafter  8

# output 2:
# Yesterday
# TOday
# TOMorrow
# DAYAfter

In [3]:
for value in days:
    print value,len(value)


yesterday 9
today 5
tomorrow 8
dayafter 8

In [6]:
days = ['yesterday','today','tomorrow','dayafter']

for value in days:
    print value,days.index(value),value[days.index(value)]


yesterday 0 y
today 1 o
tomorrow 2 m
dayafter 3 a

In [7]:
for value in days:
    print value,days.index(value),value[0:days.index(value)]


yesterday 0 
today 1 t
tomorrow 2 to
dayafter 3 day

In [8]:
for value in days:
    print value,days.index(value),value[0:days.index(value) + 1]


yesterday 0 y
today 1 to
tomorrow 2 tom
dayafter 3 daya

In [13]:
my_string = "python"
# pyt
print my_string[0:3]
print my_string[:3]
print my_string[3:6]
print my_string[3:]

print my_string[:3] + my_string[3:]


pyt
pyt
hon
hon
python

In [14]:
for value in days:
    print value[:days.index(value) + 1].upper() + value[days.index(value) + 1:]


Yesterday
TOday
TOMorrow
DAYAfter

In [17]:
# soft copy and deepcopy
print help(id)


Help on built-in function id in module __builtin__:

id(...)
    id(object) -> integer
    
    Return the identity of an object.  This is guaranteed to be unique among
    simultaneously existing objects.  (Hint: it's the object's memory address.)

None
32366752
32366752

In [19]:
a = 10
print id(a)
print id(10)
b = a
print id(b)
print id(10)


32366752
32366752
32366752
32366752

In [21]:
b = 20
print id(b)
print id(20)
print a
print id(a)


32366512
32366512
10
32366752

In [ ]:
# lists

In [22]:
# soft copy

my_lista = [1,2,3]
my_listb = my_lista

print my_lista,id(my_lista)
print my_listb,id(my_listb)


[1, 2, 3] 140162976637512
[1, 2, 3] 140162976637512

In [23]:
# is
print my_lista is my_listb


True

In [24]:
my_listb[1] = "two"
print my_listb   # [1,"two",3]
print my_lista   # [1,2,3]


[1, 'two', 3]
[1, 'two', 3]

In [25]:
my_listb = ["one","two","three"]
print my_listb
print my_lista


['one', 'two', 'three']
[1, 'two', 3]

In [28]:
# Deep copy

my_listc = ["a","b","c"]

# way 1

my_listd = my_listc[:]
print my_listd,id(my_listd)
print my_listc,id(my_listc)
print my_listc is my_listd


['a', 'b', 'c'] 140162976637080
['a', 'b', 'c'] 140163083072288
False

In [29]:
# way 2
import copy
print help(copy.deepcopy)


Help on function deepcopy in module copy:

deepcopy(x, memo=None, _nil=[])
    Deep copy operation on arbitrary Python objects.
    
    See the module's __doc__ string for more info.

None

In [30]:
my_liste = copy.deepcopy(my_listc)
print my_listc,id(my_listc)
print my_liste,id(my_liste)
print my_listc is my_liste


['a', 'b', 'c'] 140163083072288
['a', 'b', 'c'] 140162976638736
False

In [31]:
my_listc[1] ="one"
print my_listc
print my_liste


['a', 'one', 'c']
['a', 'b', 'c']

In [ ]:
# list comprehension
# https://github.com/tuxfux-hlp/Python-examples/blob/master/lists/list_comprehension.txt

In [39]:
# input -> 1,2,3,4,5,6,7,8,9,10
# output -> 2,4,6,8,10

output=[]
enter_numbers = raw_input("please enter the numbers:")
print enter_numbers,type(enter_numbers)
for num in enter_numbers.split(','):
    if int(num) % 2 == 0:
        output.append(num)


please enter the numbers:1,2,3,4,5,6,7,8,9,10
1,2,3,4,5,6,7,8,9,10 <type 'str'>

In [41]:
print output
print ",".join(output)


['2', '4', '6', '8', '10']
2,4,6,8,10

In [47]:
print 9 / 2  # quotient
print 9 % 2  # reminder


4
1

In [46]:
# usign list comprehensions
enter_numbers = raw_input("please enter the numbers:")
print ",".join([ num for num in enter_numbers.split(',') if int(num) % 2 == 0])


please enter the numbers:1,2,3,4,5,6,7,8,9,10
2,4,6,8,10

In [48]:
# example 2:
# https://github.com/tuxfux-hlp/Python-examples/blob/master/lists/list_comprehension.txt

my_sentence = "today is friday"
print [ [value.upper(),value.lower(),value.capitalize()] for value in my_sentence.split()]


[['TODAY', 'today', 'Today'], ['IS', 'is', 'Is'], ['FRIDAY', 'friday', 'Friday']]

In [ ]: