In [ ]:
# lists
# A list is a collection of elements.
# List is a collection of hetrogenous elements.
# List - Linear collection of data.
# arrays - Multidimension collection of data.
# ex: latitude and logitude.
# http://scipy.org

In [1]:
# lists
my_fruits = ['apple','banana','cherry','dates','fig']  # homogenous

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


['apple', 'banana', 'cherry', 'dates', 'fig'] <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]:
# in operation

In [6]:
print 'apple' in my_fruits


True

In [7]:
print 'Apple' in my_fruits


False

In [11]:
# example
absent = ['kumar','anu','varun','deepti']
for student in ['shravya','anu','deepti','kumar','naimisha','varun','mani']:
    if student in absent:
        continue
        #break
        #pass
    print "results of student - {}".format(student)


results of student - shravya
results of student - naimisha
results of student - mani

In [12]:
# lists support indendation
# lists support slicing

In [14]:
print my_fruits[0]
# lists are mutable - you can modify.
my_fruits[0] = 'Apple'
print my_fruits


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

In [15]:
my_string = "apple"
print my_string[0]


a

In [16]:
# string is immutable - you cannot modify.
my_string[0]='A'


---------------------------------------------------------------------------
TypeError                                 Traceback (most recent call last)
<ipython-input-16-1c725bc398c1> in <module>()
      1 # string is immutable - you cannot modify.
----> 2 my_string[0]='A'

TypeError: 'str' object does not support item assignment

In [17]:
# Iteration

In [18]:
for fruit in my_fruits:
    print fruit


Apple
banana
cherry
dates
fig

In [19]:
# functions

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


Help on built-in function append:

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

None

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


None

In [23]:
my_fruits.append('guava')

In [24]:
print my_fruits


['Apple', 'banana', 'cherry', 'dates', 'fig', 'grapes', 'guava']

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

In [27]:
print my_fruits


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

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


Help on built-in function insert:

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

None

In [29]:
my_fruits.insert(1,'apricot')

In [30]:
print my_fruits


['Apple', 'apricot', 'banana', 'cherry', 'dates', 'fig', 'grapes', 'guava', 'jackfruit', 'kiwi', 'leechi']

In [31]:
my_fruits.insert(3,'grapes')

In [34]:
print my_fruits


['Apple', 'apricot', 'banana', 'grapes', 'cherry', 'dates', 'fig', 'grapes', 'guava', 'jackfruit', 'kiwi', 'leechi']

In [33]:
# my_fruits.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 [35]:
print my_fruits.index('grapes')


3

In [37]:
print my_fruits.index('grapes',4)
print my_fruits.index('grapes',4,8)


7
7

In [38]:
# my_fruits.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 [39]:
print my_fruits.count('grapes') #2
print my_fruits.count('apple') #0


2
0

In [40]:
# my_fruits.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 [42]:
# task : 1 want to remove the first grapes
my_fruits.pop(my_fruits.index('grapes'))  # removes only one time
print my_fruits


['Apple', 'apricot', 'banana', 'cherry', 'dates', 'fig', 'guava', 'jackfruit', 'kiwi', 'leechi']

In [43]:
my_fruits.pop(20)


---------------------------------------------------------------------------
IndexError                                Traceback (most recent call last)
<ipython-input-43-dffe662ece11> in <module>()
----> 1 my_fruits.pop(20)

IndexError: pop index out of range

In [44]:
# my_fruits.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 [45]:
my_fruits.remove('Apple')

In [46]:
print my_fruits


['apricot', 'banana', 'cherry', 'dates', 'fig', 'guava', 'jackfruit', 'kiwi', 'leechi']

In [47]:
my_fruits.remove('Apple')


---------------------------------------------------------------------------
ValueError                                Traceback (most recent call last)
<ipython-input-47-43213ebe1374> in <module>()
----> 1 my_fruits.remove('Apple')

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

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


Help on built-in function reverse:

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

None

In [49]:
my_fruits.reverse()

In [50]:
print my_fruits


['leechi', 'kiwi', 'jackfruit', 'guava', 'fig', 'dates', 'cherry', 'banana', 'apricot']

In [51]:
# my_fruits.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 [52]:
print my_fruits.sort()


None

In [53]:
print my_fruits


['apricot', 'banana', 'cherry', 'dates', 'fig', 'guava', 'jackfruit', 'kiwi', 'leechi']

In [56]:
# tasks
# 5
# a
days = ['yesterday','today','tomorrow','dayafter']
print len(days)


4

In [57]:
for day in days:
    print day,len(day)


yesterday 9
today 5
tomorrow 8
dayafter 8

In [58]:
# 5b
# task
for value in days:
    print value,days.index(value)


yesterday 0
today 1
tomorrow 2
dayafter 3

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


yesterday y
today o
tomorrow m
dayafter a

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


yesterday y
today to
tomorrow tom
dayafter daya

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


Y
TO
TOM
DAYA

In [66]:
my_string="python"
print my_string[0:3]
print my_string[:3]
print my_string[3:]
print my_string[:3] + my_string[3:]


pyt
pyt
hon
python

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


Yesterday
TOday
TOMorrow
DAYAfter

In [68]:
# task 6
my_fruits = ['apple','banana','apple','banana','cherry']

In [70]:
my_duplicate = []
for value in my_fruits:
    if my_fruits.count(value) > 1:
        my_duplicate.append(value)
        my_fruits.remove(value)
        
print my_duplicate
print my_fruits


['apple', 'banana']
['apple', 'banana', 'cherry']

In [1]:
# memory  - lists
# soft copy and deep copy

In [2]:
a = 1

In [3]:
print a


1

In [4]:
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 [5]:
print id(1)
print id(a)


38732152
38732152

In [6]:
b = 1

In [12]:
print b,id(b)


2 38732128

In [8]:
b = 2

In [9]:
print b,id(b)


2 38732128

In [10]:
# is

In [11]:
print 'apple' in ['apple','banana','cherry','dates']


True

In [13]:
print a is b


False

In [14]:
c = 1

In [15]:
print id(1),id(a),id(c)


38732152 38732152 38732152

In [16]:
print c is a


True

In [17]:
# lists

In [ ]:
# soft copy

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


[1, 2, 3] 140486970798024

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


[1, 2, 3] 140486970798024

In [20]:
print a is b


True

In [21]:
print b[1]


2

In [22]:
b[1]="two"

In [23]:
print a,id(a) # [1,two,3]
print b,id(b) # [1,2,3] or [1,two,3]


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

In [24]:
a = [1,2,3]
print a,id(a)  # [1,2,3]
print b,id(b)  # [1,2,3] or [1,two,3]


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

In [25]:
# deep copy

In [26]:
c = ['one','two','three']
# deepcopy
d = c[:]
print c,id(c)
print d,id(d)


['one', 'two', 'three'] 140486970861832
['one', 'two', 'three'] 140486970850768

In [27]:
print c is d


False

In [28]:
# copy
import copy

In [29]:
e = copy.deepcopy(c)
print c,id(c)
print e,id(e)


['one', 'two', 'three'] 140486970861832
['one', 'two', 'three'] 140487438173032

In [30]:
print e is c


False

In [31]:
# sys.argv

In [33]:
# look at the example. - 
# look at add.py

In [ ]:
# convert from list to string
# string to list and vice-versa

In [39]:
# converting string to list.
my_string = "python"
Lmy_string = list(my_string)
print Lmy_string


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

In [40]:
Lmy_string[0]='T'
print Lmy_string


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

In [41]:
# converting a list to string

In [46]:
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 [47]:
print limiter.join(Lmy_string)


Tython

In [48]:
# ex: useradd kumar
# tail /etc/passwd
my_user = ['kumar','x','512','512','user kumar','/home/kumar','/bin/bash']
limiter = ':'
print limiter.join(my_user)


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

In [49]:
# converting a sentence to a list
my_sentence = "today is sunday"

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


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

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


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
['today', 'is', 'sunday']

In [53]:
Lmy_sentence[0] = 'yesterday'
print Lmy_sentence


['yesterday', 'is', 'sunday']

In [54]:
delimiter = " "
print delimiter.join(Lmy_sentence)


yesterday is sunday

In [34]:
# list comprehensions
# building list on fly.

In [35]:
num = raw_input("please enter a number:")
print num


please enter a number:1,2,3,4,5,6,7,8,9,10
1,2,3,4,5,6,7,8,9,10

In [55]:
print type(num),num


<type 'str'> 1,2,3,4,5,6,7,8,9,10

In [56]:
# output - 2,4,6,8,10

In [59]:
my_output = []
for value in num.split(','):
    if int(value) % 2 == 0:
        my_output.append(value)
print ','.join(my_output)


2,4,6,8,10

In [63]:
# list comprehension
#num = raw_input("please enter a number:")
# [output;loop;condtion]
print ','.join([ value for value in num.split(',') if int(value) % 2 == 0])


2,4,6,8,10

In [64]:
# few more example on list comprehesion.
# https://github.com/tuxfux-hlp/Python-examples/blob/master/lists/list_comprehension.txt

In [ ]: