In [ ]:
# A list is a linear representation of data.
# A indexed representation of your data.
# list vs array(multi-dimesion)
# http://scipy.org/

In [1]:
# creation of a list

my_fruits = ['apple','banana','custard','dates']
print my_fruits
print type(my_fruits)

empty_list = list()
print empty_list
print type(empty_list)

empty_list1 = []
print empty_list1
print type(empty_list1)


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

In [4]:
# in operation
print 'apple' in my_fruits
print 'Apple' in my_fruits


True
False

In [5]:
absent=['kumar','swapnil','shiva']
for student in ('shiva','srikant','sunil','kumar','tarun','swapnil','anunash'):
    if student in absent:
        continue # print all except kumar
        #break    # print shiva,srikant,sunil
        #pass     # print everything
    print "results for the student:{}".format(student)


results for the student:srikant
results for the student:sunil
results for the student:tarun
results for the student:anunash

In [6]:
# we can modify the elements of a list.
print my_fruits


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

In [16]:
# lists are iterable
for value in my_fruits:
    print value


Apple
banana
custard
dates

In [7]:
# your lists are index values
# ['apple', 'banana', 'custard', 'dates']
#    0         1         2          3

my_fruits[0]='Apple'

In [8]:
print my_fruits


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

In [10]:
my_string="python"
# p  y  t  h  o  n
# 0  1  2  3  4  5
print my_string[0]
my_string[0]="P"


p
---------------------------------------------------------------------------
TypeError                                 Traceback (most recent call last)
<ipython-input-10-60dba5be4863> in <module>()
      3 # 0  1  2  3  4  5
      4 print my_string[0]
----> 5 my_string[0]="P"

TypeError: 'str' object does not support item assignment

In [11]:
# converting string to a list and vice-versa
my_string="python"
print my_string,type(my_string)


python <type 'str'>

In [12]:
# converting a string to a list
Lmy_string=list(my_string)

In [13]:
print Lmy_string


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

In [14]:
Lmy_string[0]='J'
print Lmy_string


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

In [15]:
# conver the list back to a string
print help(my_string.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 [30]:
new_string = "".join(Lmy_string)
print my_string,new_string


python Jython

In [22]:
# useradd kumar
userdetails=['kumar','x','512','512','username kumar','/home/kumar','/bin/bash']
# make a entry in /etc/passwd files
print ':'.join(userdetails)


kumar:x:512:512:username kumar:/home/kumar:/bin/bash

In [23]:
# converting a string to a list.
# take a sequence of words.
my_sentence="today is saturday"

In [25]:
# list doesnot always work for words. It splits letter wise.
Lmy_sentence = list(my_sentence)
print Lmy_sentence


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

In [26]:
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 [28]:
Lmy_sentence = my_sentence.split()
print Lmy_sentence


['today', 'is', 'saturday']

In [29]:
# modify the list
Lmy_sentence[0] ="Tomorrow"
Lmy_sentence[2] ="sunday."
print Lmy_sentence


['Tomorrow', 'is', 'sunday.']

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


Tomorrow is sunday.

In [32]:
# Function
print my_fruits


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

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


Help on built-in function append:

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

None

In [35]:
my_fruits.append('gauva')
print my_fruits


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

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

In [38]:
print my_fruits


['Apple', 'banana', 'custard', 'dates', 'gauva', 'jackfruit', 'kiwi', 'leechi']

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


Help on built-in function insert:

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

None

In [41]:
my_fruits.insert(4,'grapes')

In [42]:
print my_fruits


['Apple', 'banana', 'custard', 'dates', 'grapes', 'gauva', 'jackfruit', 'kiwi', 'leechi']

In [43]:
# 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 [44]:
print my_fruits.index('grapes') # 4
print my_fruits.index('custard') # 2


4
2

In [45]:
my_fruits.insert(4,'grapes')
print my_fruits


['Apple', 'banana', 'custard', 'dates', 'grapes', 'grapes', 'gauva', 'jackfruit', 'kiwi', 'leechi']

In [47]:
print my_fruits.index('grapes',5)


5

In [48]:
# 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 [50]:
print my_fruits.pop() # leechi


leechi

In [51]:
print my_fruits


['Apple', 'banana', 'custard', 'dates', 'grapes', 'grapes', 'gauva', 'jackfruit', 'kiwi']

In [52]:
print my_fruits.pop(4)
print my_fruits


grapes
['Apple', 'banana', 'custard', 'dates', 'grapes', 'gauva', 'jackfruit', 'kiwi']

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


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

IndexError: pop index out of range

In [55]:
# remove
print help(my_fruits.remove)
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
['Apple', 'banana', 'custard', 'dates', 'grapes', 'gauva', 'jackfruit', 'kiwi']

In [56]:
my_fruits.remove('grapes')

In [57]:
print my_fruits


['Apple', 'banana', 'custard', 'dates', 'gauva', 'jackfruit', 'kiwi']

In [58]:
my_fruits.remove('grapes')


---------------------------------------------------------------------------
ValueError                                Traceback (most recent call last)
<ipython-input-58-9bd377028339> in <module>()
----> 1 my_fruits.remove('grapes')

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

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


Help on built-in function reverse:

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

None

In [62]:
print my_fruits
print my_fruits.reverse()
print my_fruits


['Apple', 'banana', 'custard', 'dates', 'gauva', 'jackfruit', 'kiwi']
None
['kiwi', 'jackfruit', 'gauva', 'dates', 'custard', 'banana', 'Apple']

In [63]:
# 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 [64]:
my_fruits.sort() # ascending order

In [65]:
print my_fruits


['Apple', 'banana', 'custard', 'dates', 'gauva', 'jackfruit', 'kiwi']

In [67]:
my_fruits.sort(reverse=True) # descending order
print my_fruits


['kiwi', 'jackfruit', 'gauva', 'dates', 'custard', 'banana', 'Apple']

Task1 days = ['yesteday','today','tomorrow','dayafter']

yesterday 9 today 5 tomorrow 8 dayafter 8

Task2: Yesterday TOday TOMorrow DAYAafter


In [69]:
days = ['yesterday','today','tomorrow','dayafter']
for value in days:
    print value,len(value)


yesterday 9
today 5
tomorrow 8
dayafter 8

In [70]:
days = ['yesterday','today','tomorrow','dayafter']
for value in days:
    print value


yesterday
today
tomorrow
dayafter

In [73]:
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 [80]:
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 [81]:
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 [79]:
my_string="python"
print my_string[:3]
print my_string[3:]
print my_string[:3] + my_string[3:]
print my_string[0]
print my_string[0:0] #[start:end]


pyt
hon
python
p


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


Yesterday
TOday
TOMorrow
DAYAfter

In [82]:
# aliasing
a = 1

In [83]:
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 [85]:
print id(1),id(a)


33919352 33919352

In [86]:
b = 1

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


33919352 33919352

In [88]:
b = 2

In [90]:
print id(a),id(b)


33919352 33919328

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


33919352 33919328

In [2]:
# softcopy,deepcopy,shallowcopy

In [4]:
# softcopy
a = [1,2,3]
print id(a)
print id([1,2,3])
print id(a[0])
print id(a[1])
print id(a[2])


140659991823208
140659860212192
38211960
38211936
38211912

In [5]:
# copy a list
b = a
print id(b)
print id(a)


140659991823208
140659991823208

In [8]:
# is
print a is b
print a
print b


True
[1, 2, 3]
[1, 2, 3]

In [9]:
# softcopy

print b[1]
b[1] = "two"


2

In [10]:
print b  # 1,two,3
print a  # 1,2,3 -> 1,two,3


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

In [11]:
b = ['one','two','three']

In [12]:
print a
print b


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

In [13]:
# deepcopy

a = [1,2,3]
print id(a)


140659860204936

In [14]:
# use case 1:
b = a[:]
print a,b
print id(a),id(b)
print a is b


[1, 2, 3] [1, 2, 3]
140659860204936 140659860642272
False

In [16]:
b[1] ='two'
print a
print b


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

In [17]:
# use case 2:
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 [19]:
c = copy.deepcopy(a)
print a
print c
print id(a),id(c)
print a is c


[1, 2, 3]
[1, 2, 3]
140659860204936 140659851272136
False

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

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

In [31]:
values = raw_input("please enter the numbers:")
even =[]
print values,type(values)
# parse via values one by one,convert to integers,save even in list,later convert list to string
for value in values.split(','):
    if int(value) % 2 == 0:  # % looks for a reminder , / looks for a quotient
        even.append(value)
print even


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'>
['2', '4', '6', '8', '10']

In [32]:
print ",".join(even)


2,4,6,8,10

In [35]:
# list comprenesion
# https://github.com/tuxfux-hlp/Python-examples/blob/master/lists/list_comprehension.txt
values = raw_input("please enter the numbers:")
print ",".join([ value for value in values.split(',') if int(value) % 2 == 0])


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

In [ ]: