In [ ]:
# Lists
# List is a linear representation of hetrogeneous data .
# Arrays(numpy) and Lists are not synonymous.
# https://scipy.org/

In [1]:
my_fruits = ["Apple","banana","cherry","dates"]

In [2]:
print my_fruits,type(my_fruits)


['Apple', 'banana', 'cherry', 'dates'] <type 'list'>

In [3]:
my_empty = []
print my_empty,type(my_empty)


[] <type 'list'>

In [4]:
my_empty = list()
print my_empty,type(my_empty)


[] <type 'list'>

In [5]:
# list - iterator
for value in my_fruits:
    print value


Apple
banana
cherry
dates

In [ ]:
# list support - indexing,slicing.

In [6]:
print my_fruits[3]
print my_fruits[-1]


dates
dates

In [7]:
# cherry
print my_fruits[2][2]


e

In [8]:
# slicing
print my_fruits[1:3]


['banana', 'cherry']

In [ ]:
# in

In [10]:
print 'apple' in my_fruits
print 'Apple' in my_fruits


False
True

In [11]:
# list are mutable.
print my_fruits


['Apple', 'banana', 'cherry', 'dates']

In [12]:
my_fruits[1]="Banana"
print my_fruits


['Apple', 'Banana', 'cherry', 'dates']

In [13]:
# string cannot be modified - immutable.
my_string="banana"
my_string[0]="B"


---------------------------------------------------------------------------
TypeError                                 Traceback (most recent call last)
<ipython-input-13-4d0912d41d59> in <module>()
      1 # string
      2 my_string="banana"
----> 3 my_string[0]="B"

TypeError: 'str' object does not support item assignment

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

In [14]:
# string
my_string="python"

# convering a string to a list
Lmy_string = list(my_string)
print Lmy_string


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

In [15]:
# modified list.
Lmy_string[0]="T"
print Lmy_string


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

In [26]:
# convert the list back to string
limiter=""
print help(limiter.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 [28]:
print limiter.join(Lmy_string)
print ",".join(Lmy_string)


Tython
T,y,t,h,o,n

In [31]:
# my_sentence
my_sentence = "Today is thursday"
print my_sentence


Today is thursday

In [33]:
Lmy_sentence = list(my_sentence)
print Lmy_sentence


['T', 'o', 'd', 'a', 'y', ' ', 'i', 's', ' ', 't', 'h', 'u', 'r', 's', 'd', 'a', 'y']

In [34]:
# split
print help(my_sentence.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

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


['Today', 'is', 'thursday']

In [37]:
Lmy_sentence[2]="Friday"
print Lmy_sentence


['Today', 'is', 'Friday']

In [38]:
# revert it back to a string
limiter=" "
print limiter.join(Lmy_sentence)


Today is Friday

In [40]:
#!/usr/bin/python
# continue: you can skip an iteration
absent = ['chitu','ravi','law','akshit','kumar']
for student in ['chitu','soumi','ravi','kumar','law','aditya','akshit','krishna']:
	if student in absent:
		continue
		#break
		#pass
	print "results of student - {} ".format(student)


results of student - soumi 
results of student - aditya 
results of student - krishna 

In [43]:
# i want to find out the students who are absent and also there in studnet list.
absent = ['chitu','ravi','law','akshit','kumar']
student = ['chitu','soumi','ravi','law','aditya','akshit','krishna']

for stu in absent:
    if stu not in student:
        continue
    print "name of the student who is absent - {}".format(stu)


name of the student who is absent - chitu
name of the student who is absent - ravi
name of the student who is absent - law
name of the student who is absent - akshit

In [ ]:
# Assignements
# https://github.com/sambapython/python/blob/master/assignments.txt
# reverse a list -wihout a function.
l=[1,2,3,5,7,8,9,10,11,12,13,20,22,23,24,25,26,27,20,21,22,4] output = [[1, 2, 3], [5], [7, 8, 9, 10, 11, 12, 13], [20], [22, 23, 24, 25, 26, 27], [20, 21, 22], [4]]

In [ ]:
# functions

In [1]:
my_fruits = ['apple','banana','cherry','dates']

In [2]:
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 [3]:
# append
print help(my_fruits.append)


Help on built-in function append:

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

None

In [4]:
my_fruits.append('fig')

In [5]:
print my_fruits


['apple', 'banana', 'cherry', 'dates', 'fig']

In [6]:
# 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 [7]:
my_fruits.extend(['grapes','jackfruit','kiwi'])

In [8]:
print my_fruits


['apple', 'banana', 'cherry', 'dates', 'fig', 'grapes', 'jackfruit', 'kiwi']

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


Help on built-in function insert:

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

None

In [11]:
my_fruits.insert(6,'guava')

In [12]:
print my_fruits


['apple', 'banana', 'cherry', 'dates', 'fig', 'grapes', 'guava', 'jackfruit', 'kiwi']

In [13]:
# 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 [14]:
print my_fruits.index('guava')


6

In [17]:
my_fruits.insert(0,'guava')
print my_fruits
print my_fruits.index('guava') # first guava
print my_fruits.index('guava',1)


['guava', 'guava', 'guava', 'apple', 'banana', 'cherry', 'dates', 'fig', 'grapes', 'guava', 'jackfruit', 'kiwi']
0
1

In [19]:
# 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 [20]:
print my_fruits.count('guava')


4

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


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

In [22]:
print my_fruits


['guava', 'guava', 'guava', 'apple', 'banana', 'cherry', 'dates', 'fig', 'grapes', 'guava', 'jackfruit', 'kiwi']

In [23]:
my_fruits.pop(0)


Out[23]:
'guava'

In [24]:
print my_fruits


['guava', 'guava', 'apple', 'banana', 'cherry', 'dates', 'fig', 'grapes', 'guava', 'jackfruit', 'kiwi']

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


kiwi

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


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

IndexError: pop index out of range

In [27]:
# remove
print help(my_fruits.remove)


Help on built-in function remove:

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

None

In [28]:
print my_fruits.remove('guava')


None

In [29]:
print my_fruits


['guava', 'apple', 'banana', 'cherry', 'dates', 'fig', 'grapes', 'guava', 'jackfruit']

In [31]:
# sort
print help(my_fruits.sort)
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 [32]:
print my_fruits


['apple', 'banana', 'cherry', 'dates', 'fig', 'grapes', 'guava', 'guava', 'jackfruit']

In [33]:
print my_fruits.sort(reverse=True)


None

In [34]:
print my_fruits


['jackfruit', 'guava', 'guava', 'grapes', 'fig', 'dates', 'cherry', 'banana', 'apple']

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


Help on built-in function reverse:

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

None
None

In [36]:
print my_fruits


['apple', 'banana', 'cherry', 'dates', 'fig', 'grapes', 'guava', 'guava', 'jackfruit']

In [38]:
# task

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

# task1
# 
# yesterday 9
# today    5
# tomorrow 8
# dayafter 8

# task2
# Yesterday
# TOday
# TOMorrow
# DAYAfter

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


yesterday 9
today 5
tomorrow 8
dayafter 8

In [42]:
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 [44]:
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 [48]:
for value in days:
    print value[:days.index(value) + 1].upper()


Y
TO
TOM
DAYA

In [47]:
my_string="python"
print my_string[0:3] # pyt
print my_string[:3]  # pyt
print my_string[3:6] # hon
print my_string[3:]
print my_string[:3] + my_string[3:]


pyt
pyt
hon
hon
python

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


Yesterday
TOday
TOMorrow
DAYAfter

In [ ]:
# sys.argv

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

In [53]:
square=[]
multiples = []
for value in range(1,100):
    square.append(value*value)
for value in square:
    if value % 2 == 0 and value % 3 == 0:
        multiples.append(value)
print multiples


[36, 144, 324, 576, 900, 1296, 1764, 2304, 2916, 3600, 4356, 5184, 6084, 7056, 8100, 9216]

In [57]:
# list comprehension
# [value looping condition]
print [ value for value in [ value*value for value in range(1,100) ] if value % 2 == 0 and value % 3 == 0 ]


[36, 144, 324, 576, 900, 1296, 1764, 2304, 2916, 3600, 4356, 5184, 6084, 7056, 8100, 9216]

In [63]:
# example2
# 2,4,6,8,10
num = raw_input("please enter a number:")
print num,type(num) 
print ",".join([value for value in num.split(',') if int(value) % 2 == 0])


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

In [ ]:
# softcopy and deepcopy

In [1]:
a = 1

In [3]:
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

In [2]:
print id(1),id(a)


27566456 27566456

In [4]:
b = 1

In [5]:
print id(b),id(1)


27566456 27566456

In [6]:
# is
print a is b


True

In [9]:
# in
print b in [1,2]


True

In [10]:
b = 2

In [11]:
print b


2

In [12]:
print id(1),id(2),id(a),id(b)


27566456 27566432 27566456 27566432

In [13]:
# lists

In [ ]:
# two lists sharing similar memory blocks and both get modified when we try to modify one element
# this features is called as soft copy.

In [14]:
weeks = ['sun','mon','tue']

In [15]:
print id(weeks),id(weeks[0]),id(weeks[1]),id(weeks[2])


140700932997416 140701079789240 140701106579096 140701079789040

In [16]:
weeks1 = weeks

In [19]:
print weeks1
print id(weeks1),id(weeks1[0]),id(weeks1[1]),id(weeks1[2])


['sun', 'mon', 'tue']
140700932997416 140701079789240 140701106579096 140701079789040

In [20]:
print weeks is weeks1


True

In [22]:
print weeks[2]
weeks[2] = "wed"
print weeks1  #["sun","mon","tue"]
print weeks   #["sun","mon","wed"]


wed
['sun', 'mon', 'wed']
['sun', 'mon', 'wed']

In [23]:
# use case
weeks = ['thu','fri','sat']
print weeks
print weeks1


['thu', 'fri', 'sat']
['sun', 'mon', 'wed']

In [26]:
# deep copy
a = [1,2,3]
print a,id(a),id(a[0]),id(a[1]),id(a[2])


[1, 2, 3] 140700932546784 27566456 27566432 27566408

In [25]:
# case i
b = a[:]
print b,id(b),id(b[0]),id(b[1]),id(b[2])


[1, 2, 3] 140700932542336 27566456 27566432 27566408

In [28]:
b[1]="two"
print b
print a


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

In [30]:
# copy
import copy
print dir(copy)


['Error', 'PyStringMap', '_EmptyClass', '__all__', '__builtins__', '__doc__', '__file__', '__name__', '__package__', '_copy_dispatch', '_copy_immutable', '_copy_inst', '_copy_with_constructor', '_copy_with_copy_method', '_deepcopy_atomic', '_deepcopy_dict', '_deepcopy_dispatch', '_deepcopy_inst', '_deepcopy_list', '_deepcopy_method', '_deepcopy_tuple', '_keep_alive', '_reconstruct', '_test', 'copy', 'deepcopy', 'dispatch_table', 'error', 'name', 't', 'weakref']

In [31]:
c = copy.deepcopy(a)
print c,a
print id(c),id(a)


[1, 2, 3] [1, 2, 3]
140700932548368 140700932546784

In [ ]:
#

In [ ]: