In [ ]:
# what is a list?
# List is a collection of data.
# Lists can store both homogenous and hetrogenous data.
# list vs array
# array : http://tinyurl.com/TconSeminars

In [2]:
# lists are indexed.
my_fruits = ['apple','banana','cherry','dates']
print my_fruits,type(my_fruits)


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

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


[] <type 'list'>

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


[] <type 'list'>

In [5]:
# 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[0]


apple

In [6]:
# slicing
print my_fruits[0:3]


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

In [7]:
# lists are mutable. - you can modify the lists.
my_string = "python"
print my_string[0]
my_string[0] = "P"


p
---------------------------------------------------------------------------
TypeError                                 Traceback (most recent call last)
<ipython-input-7-a16b53304d79> 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 [9]:
print my_fruits
print my_fruits[0]
my_fruits[0]='Apple'
print my_fruits


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

In [11]:
# in
print 'Apple' in my_fruits
print 'orange' in my_fruits


True
False

In [14]:
# example on in
#!/usr/bin/python
# continue : its skips an iteration.

absent = ['sunil','raj','madhuri','kumar']
for student in ['rajni','madhuri','priya','kumar','sunil','raj','praveen']:
	if student in absent:
		continue
		#break
		#pass
	print "results for the student - {}".format(student)


results for the student - rajni
results for the student - priya
results for the student - praveen

In [16]:
# converting string to list and vice-versa.
# case I
# converted a string to list.
my_string="python"
Lmy_string = list(my_string)
print my_string,Lmy_string


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

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


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

In [21]:
# we have a list and need to convert it to string
# you converted a list to string.
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
Tython

In [23]:
# case II
my_sentence="Today is friday"
print list(my_sentence)
print help(my_sentence.split)


['T', 'o', 'd', 'a', 'y', ' ', 'i', 's', ' ', 'f', 'r', 'i', 'd', 'a', 'y']
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 [25]:
Lmy_string = my_sentence.split()
print Lmy_string
Lmy_string[2]='Thursday'
print Lmy_string


['Today', 'is', 'friday']
['Today', 'is', 'Thursday']

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


Today is Thursday

In [5]:
# Memory of lists in python.
# soft copy,deep copy,shallow copy

a = 1
print help(id)
print a,id(1),id(a)

b = a
print b,id(b)

# is
print a is b

# lets modify the value of b
b = 3
print b,id(b),id(3)
print a,id(a)


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
1 33239416 33239416
1 33239416
True
3 33239368 33239368
1 33239416

In [11]:
# lists
my_list = [1,2,3]
print id(my_list),my_list
my_list1 = my_list
print id(my_list1),my_list1

# soft copy: both the objects linked to same memory block
my_list[1] = "two"
print my_list  # [1,'two',3]
print my_list1 # [1,2,3]
my_list = ["one","two","three"]
print my_list
print my_list1
print id(my_list),id(my_list1)


140242684691592 [1, 2, 3]
140242684691592 [1, 2, 3]
[1, 'two', 3]
[1, 'two', 3]
['one', 'two', 'three']
[1, 'two', 3]
140242561477016 140242684691592

In [17]:
# deep copy
my_list = [1,2,3]
print my_list,id(my_list)
my_list1 = my_list[:]
print my_list1,id(my_list1)
my_list[1]="two"
print my_list
print my_list1

# deep copy
import copy
print dir(copy)
my_list2 = copy.deepcopy(my_list)
print my_list2,id(my_list2)
print my_list,id(my_list)

# is
print my_list is my_list2


[1, 2, 3] 140242561475792
[1, 2, 3] 140242561475720
[1, 'two', 3]
[1, 2, 3]
['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']
[1, 'two', 3] 140242561481544
[1, 'two', 3] 140242561475792
False

In [18]:
# my_functions

my_fruits = ['apple','banana','cherry','dates']
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 [20]:
# append
print help(my_fruits.append)
my_fruits.append('fig')
print my_fruits


Help on built-in function append:

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

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

In [22]:
# extend
print help(my_fruits.extend)
my_fruits.extend(['grapes','jackfruit','kiwi'])
print my_fruits


Help on built-in function extend:

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

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

In [26]:
# index
print help(my_fruits.index)
print my_fruits.index('grapes')


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
5

In [27]:
# insert
print help(my_fruits.insert)
my_fruits.insert(5,'gauva')
print my_fruits


Help on built-in function insert:

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

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

In [29]:
# pop
print help(my_fruits.pop)
print my_fruits.pop()
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
kiwi
['apple', 'banana', 'cherry', 'dates', 'fig', 'gauva', 'grapes', 'jackfruit']

In [30]:
# remove
print help(my_fruits.remove)
print my_fruits.remove('dates')
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', 'banana', 'cherry', 'fig', 'gauva', 'grapes', 'jackfruit']

In [31]:
# count
print help(my_fruits.count)
print my_fruits.count('cherry')
print my_fruits


Help on built-in function count:

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

None
1
['apple', 'banana', 'cherry', 'fig', 'gauva', 'grapes', 'jackfruit']

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


Help on built-in function reverse:

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

None
['apple', 'banana', 'cherry', 'fig', 'gauva', 'grapes', 'jackfruit']
None
['jackfruit', 'grapes', 'gauva', 'fig', 'cherry', 'banana', 'apple']

In [36]:
# sort
print help(my_fruits.sort)
print my_fruits.sort()
print my_fruits
print my_fruits.sort(reverse=True)
print my_fruits


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
None
['apple', 'banana', 'cherry', 'fig', 'gauva', 'grapes', 'jackfruit']
None
['jackfruit', 'grapes', 'gauva', 'fig', 'cherry', 'banana', 'apple']
# task my_days = ['yesterday','today','tomorrow','dayafter'] # task1: output yesterday 9 today 5 tomorrow 8 dayafter 8 # task2: output Yesterday TOday TOMorrow DAYAfter

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


yesterday 9
today 5
tomorrow 8
dayafter 8

In [42]:
# task2
for value in my_days:
    print value,my_days.index(value),value[my_days.index(value)],value[:my_days.index(value) + 1]


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

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


pyt
hon
python

In [43]:
for value in my_days:
    print value[:my_days.index(value) + 1].upper() + value[my_days.index(value) + 1:]


Yesterday
TOday
TOMorrow
DAYAfter

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

In [1]:
# without list comprehnesions 
# 1,2,3,4,5,6,7,8,9,10
# 2,4,6,8,10
num = raw_input("please enter a number:")
print num,type(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 <type 'str'>

In [2]:
Lnum = num.split(',')
print Lnum,type(Lnum)


['1', '2', '3', '4', '5', '6', '7', '8', '9', '10'] <type 'list'>

In [3]:
Leven = []
for value in Lnum:
    if int(value) % 2 == 0:
        Leven.append(value)

In [5]:
print Leven
print ",".join(Leven)


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

In [9]:
# list comprehensions
# [print;condition;statements]
# [3,1,2]
print ",".join([ value for value in num.split(',') if int(value) % 2 == 0])


2,4,6,8,10

In [11]:
# example 2
my_string="today is saturday"
[ [value.upper(),value.capitalize(),value.lower()] for value in my_string.split()]


Out[11]:
[['TODAY', 'Today', 'today'],
 ['IS', 'Is', 'is'],
 ['SATURDAY', 'Saturday', 'saturday']]

In [ ]: