In [ ]:
# Lists
# A collection of elements - homongenous/hetrogenous collection of data.
# list and array are different - python
# list is a linear collection of data.
# Array is a n dimension representation of data. ( numpy)
# http://scipy.org/
# TODO : ADD THE LINK FOR THE SEMINARS

In [3]:
my_fruits = ['apple','banana','cherry','dates']
print my_fruits,type(my_fruits)

my_empty = []
print my_empty,type(my_empty)

my_emtpy = list()
print my_empty,type(my_empty)


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

In [4]:
# indexing
my_fruits = ['apple','banana','cherry','dates']
#              0        1        2       3      # +ve indexing or left to right
#              -4       -3       -2      -1     # -ve indexing or right to left

print my_fruits[1]


banana

In [7]:
# slicing
print my_fruits[0:3]
# for(i=0;i<=4;i+2)
print my_fruits[::2]
print my_fruits[1::2]


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

In [9]:
# in operator
print 'apple' in my_fruits
print 'gauva' in my_fruits


True
False

In [12]:
# task
absent = ['kumar','shalini','sandy']
for student in ['naren','sandy','kumar','shalini','sushma']:
	if student in absent:
		continue
		#break
		#pass
	print "results of student - {}".format(student)


results of student - naren
results of student - sushma

In [ ]:
# lists are mutable 
# strings are immutable

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


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

In [15]:
# string
my_string = "python"
my_string[0]="P"


---------------------------------------------------------------------------
TypeError                                 Traceback (most recent call last)
<ipython-input-15-f8a878169bfa> in <module>()
      1 # string
      2 my_string = "python"
----> 3 my_string[0]="P"

TypeError: 'str' object does not support item assignment

In [16]:
# lists are iterable.

for value in my_fruits:
    print value


Apple
banana
cherry
dates

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

## convert a string to a list.
my_string="python"
Lmy_string = list(my_string)
print Lmy_string,type(Lmy_string)


['p', 'y', 't', 'h', 'o', 'n'] <type 'list'>

In [19]:
# list to string
Lmy_string[0]='T'
print Lmy_string


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

In [23]:
delimiter=""
print help(delimiter.join)
print delimiter.join(Lmy_string)


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
T:y:t:h:o:n

In [25]:
# case - II
my_string = "Today is sunday"
Lmy_string=list(my_string)
print Lmy_string


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

In [26]:
print help(my_string.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 [29]:
Lmy_string = my_string.split()
print Lmy_string
Lmy_string[0]='Tomorrow'
print Lmy_string


['Today', 'is', 'sunday']
['Tomorrow', 'is', 'sunday']

In [30]:
# convert the list back to string
limiter=" "
print limiter.join(Lmy_string)


Tomorrow is sunday

In [33]:
# Function

print my_fruits
print dir(my_fruits)
print help(dir)


['Apple', 'banana', 'cherry', 'dates']
['__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']
Help on built-in function dir in module __builtin__:

dir(...)
    dir([object]) -> list of strings
    
    If called without an argument, return the names in the current scope.
    Else, return an alphabetized list of names comprising (some of) the attributes
    of the given object, and of attributes reachable from it.
    If the object supplies a method named __dir__, it will be used; otherwise
    the default dir() logic is used and returns:
      for a module object: the module's attributes.
      for a class object:  its attributes, and recursively the attributes
        of its bases.
      for any other object: its attributes, its class's attributes, and
        recursively the attributes of its class's base classes.

None

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]:
print my_fruits.append('figs')
print my_fruits


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

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 [38]:
my_fruits.extend(['gauva','jackfruit','kiwi'])
print my_fruits


['Apple', 'banana', 'cherry', 'dates', 'figs', 'gauva', 'jackfruit', 'kiwi']

In [39]:
# 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 [40]:
my_fruits.index('gauva')


Out[40]:
5

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


Help on built-in function insert:

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

None

In [42]:
my_fruits.insert(5,'grapes')
print my_fruits


['Apple', 'banana', 'cherry', 'dates', 'figs', 'grapes', 'gauva', 'jackfruit', 'kiwi']

In [43]:
# 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 [44]:
print my_fruits.count('gauva')


1

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


['Apple', 'banana', 'cherry', 'dates', 'figs', 'grapes', 'gauva', 'jackfruit', 'kiwi', 'gauva']
2

In [46]:
# 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 [47]:
print my_fruits.pop(my_fruits.index('jackfruit'))


jackfruit

In [48]:
print my_fruits


['Apple', 'banana', 'cherry', 'dates', 'figs', 'grapes', 'gauva', 'kiwi', 'gauva']

In [49]:
print my_fruits.pop()


gauva

In [50]:
print my_fruits


['Apple', 'banana', 'cherry', 'dates', 'figs', 'grapes', 'gauva', 'kiwi']

In [51]:
print my_fruits.pop(20)


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

IndexError: pop index out of range

In [52]:
# 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 [53]:
print my_fruits.remove('grapes')
print my_fruits


None
['Apple', 'banana', 'cherry', 'dates', 'figs', 'gauva', 'kiwi']

In [54]:
print my_fruits.remove('grapes')


---------------------------------------------------------------------------
ValueError                                Traceback (most recent call last)
<ipython-input-54-2be81d71bbd3> in <module>()
----> 1 print my_fruits.remove('grapes')

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

In [55]:
# 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
['kiwi', 'gauva', 'figs', 'dates', 'cherry', 'banana', 'Apple']

In [56]:
# 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 [57]:
print my_fruits.sort(reverse=True)
print my_fruits


None
['kiwi', 'gauva', 'figs', 'dates', 'cherry', 'banana', 'Apple']

In [58]:
print my_fruits.sort()
print my_fruits


None
['Apple', 'banana', 'cherry', 'dates', 'figs', 'gauva', 'kiwi']
# task1 -------- Part 1: days = ['yesterday','today','tomorrow','dayafter'] yesterday 9 today 5 tomorrow 8 dayafter 8 Part 2: Yesterday TOday TOMorrow DAYAfter Task2 ------ # input my_fruits = ['apple','banana','apple','banana','cherry'] # output duplicate = ['apple','banana'] my_fruits = ['apple','banana','cherry] Task3 ------ num = raw_input("please enter a number:") # give num as 1,2,3,4,5,6,7,8,9,10 i want the output as 2,4,6,8,10

In [18]:
# task1
days = ['yesterday','today','tomorrow','dayafter']

# part1
# len
for value in days:
    print value,len(value)


yesterday 9
today 5
tomorrow 8
dayafter 8

In [25]:
# part 2
for value in days:
    print value,days.index(value),value[days.index(value)],value[:days.index(value) + 1]


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

In [1]:
my_string="python"
print my_string[:3]
print my_string[3:]
print my_string[:3] + my_string[3:]


pyt
hon
python

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


Yesterday
TOday
TOMorrow
DAYAfter

In [22]:
# task2
my_fruits = ['apple','banana','apple','banana','cherry']
duplicate=[]
for value in my_fruits:
    if my_fruits.count(value) > 1:
        if value in duplicate:
            pass
        else:
            duplicate.append(value)
        my_fruits.remove(value)
print my_fruits,duplicate


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

In [6]:
# task3

my_even = []
num = raw_input("please enter a number")
print num,type(num)
Lmy_num = num.split(',')
print Lmy_num
for value in Lmy_num:
    if int(value) % 2 == 0:
        my_even.append(value)
print ",".join(my_even)


please enter a number1,2,3,4,5,6,7,8,9,10
1,2,3,4,5,6,7,8,9,10 <type 'str'>
['1', '2', '3', '4', '5', '6', '7', '8', '9', '10']
2,4,6,8,10

In [10]:
# list comprehnesions
# https://github.com/tuxfux-hlp/Python-examples/blob/master/lists/list_comprehension.txt
# [ print ; condition ; statement ]
num = raw_input("please enter a number:")
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
2,4,6,8,10

In [12]:
# 
my_string = "today is sunday"
# output
# capitalize,upper,lower
print [[value.capitalize(),value.upper(),value.lower()] for value in my_string.split()]


[['Today', 'TODAY', 'today'], ['Is', 'IS', 'is'], ['Sunday', 'SUNDAY', 'sunday']]

In [1]:
# memory allocation in list
a = 10

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(a)
print id(10)


11153568
11153568

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


10 10
11153568 11153568 11153568

In [4]:
# is
print  b is a


True

In [5]:
b = 20
print a,b
print id(a),id(b),id(10),id(20)


10 20
11153568 11153328 11153568 11153328

In [7]:
# lists
# soft and deepcopy

# softcopy : both your labels(La,Lb) are refering to same memory block.
La = ["one","two","three"]
print La,id(La)
Lb = La
print Lb,id(Lb)
print La is Lb


['one', 'two', 'three'] 140424628996432
['one', 'two', 'three'] 140424628996432
True

In [8]:
La[1] = "2"
print La
print Lb


['one', '2', 'three']
['one', '2', 'three']

In [9]:
La = [5,6,7]
print La
print Lb


[5, 6, 7]
['one', '2', 'three']

In [10]:
# deep copy
C = [1,2,3]

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 [11]:
D = copy.deepcopy(C)
print D,C,id(D),id(C)
print C is D


[1, 2, 3] [1, 2, 3] 140424629434344 140424628938944
False

In [12]:
E = C[:]
print E,C,id(E),id(C)
print E is C


[1, 2, 3] [1, 2, 3] 140424629861912 140424628938944
False

In [ ]: