In [1]:
# lists
# list is a sequence of values - homongenous list or hetrogenous list
# list vs arrays
# list is linear representation of data.
# array is n dimensional representation of data.
# https://scipy.org/

In [1]:
# how to create a list
my_fruits = ['apple','banana','cherry','dates']
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 support indexing
# my_fruits = ['apple','banana','cherry','dates']
#                 0        1         2      3     # +ve index or left to right
#                -4        -3        -2     -1    # -ve index or right to left

In [6]:
# indexing
print my_fruits[0]


apple

In [7]:
print my_fruits[-4]


apple

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


['banana', 'cherry']

In [9]:
# we can modify the values.
print my_fruits
my_fruits[0]='Apple'
print my_fruits


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

In [10]:
my_string="apple"
print my_string[0]
my_string[0]='A'


a
---------------------------------------------------------------------------
TypeError                                 Traceback (most recent call last)
<ipython-input-10-e6294aac8af9> in <module>()
      1 my_string="apple"
      2 print my_string[0]
----> 3 my_string[0]='A'

TypeError: 'str' object does not support item assignment

In [12]:
# in operator
print my_fruits
print 'apple' in my_fruits
print 'Apple' in my_fruits


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

In [13]:
absentee = ['bibha','kumar','ashish']
for student in ['bibha','ansh','kumar','sri','ashish','ashok']:
	if student in absentee:
		continue
		#break
		#pass
	print "result for the - {}".format(student)


result for the - ansh
result for the - sri
result for the - ashok

In [14]:
# converting a list to string and a string to a list
my_string="python"

In [15]:
# convert a string to a list
Lmy_string = list(my_string)
print Lmy_string


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

In [20]:
# modify p to t
Lmy_string[0]='T'
print Lmy_string
# list to a string
new_string=''
print help(new_string.join)
print new_string.join(Lmy_string)


['T', 'y', 't', 'h', 'o', 'n']
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 [21]:
# example2:
my_sentence="today is saturday"

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


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

In [23]:
# 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 [25]:
# convert a string to a list
Lmy_sentence=my_sentence.split()
print Lmy_sentence
Lmy_sentence[-1]='Friday'
print Lmy_sentence


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

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


today is Friday

In [27]:
# khyaathi:x:1000:1000:KHYAATHI,,,:/home/khyaathi:/bin/bash
# useradd khyaathi
my_user=['khyaathi','x','1000','1000','khyaathi home','/home/khyaathi','/bin/bash']

In [30]:
print my_user
print ':'.join(my_user)
print ','.join(my_user)


['khyaathi', 'x', '1000', '1000', 'khyaathi home', '/home/khyaathi', '/bin/bash']
khyaathi:x:1000:1000:khyaathi home:/home/khyaathi:/bin/bash
khyaathi,x,1000,1000,khyaathi home,/home/khyaathi,/bin/bash

In [2]:
# Function in a list
print my_fruits


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

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


Help on built-in function append:

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

None

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


None

In [6]:
print my_fruits


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

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

In [10]:
# insert
print help(my_fruits.insert)
my_fruits.insert(0,'apricot')
print my_fruits


Help on built-in function insert:

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

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

In [11]:
# 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 [12]:
# use case
my_fruits.insert(0,'grapes')
print my_fruits


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

In [15]:
print my_fruits.index('grapes')
print my_fruits.index('grapes',1)


0
7

In [16]:
# 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 [17]:
print my_fruits.count('grapes')


2

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


Help on built-in function reverse:

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

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

In [20]:
# sort
# ascending or descending

In [22]:
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 [23]:
# ascending
my_fruits.sort()
print my_fruits


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

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


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

In [25]:
# 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 [26]:
# i want to remove grapes
my_fruits.pop(2)


Out[26]:
'grapes'

In [27]:
print my_fruits


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

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


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

IndexError: pop index out of range

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


['kiwi', 'jackfruit', 'gauva', 'dates', 'cherry', 'banana', 'apricot', 'apple']

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


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

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

In [52]:
# example1:
my_trainings = ['python','django','python','django','python','devops']
# my_trainings = ['python','django','devops']
# my_duplicates = ['python','django']

In [53]:
# soft copy and deep copy.
my_duplicates=[]
for value in my_trainings[:]:
    print "value- {}".format(value)
    if my_trainings.count(value) > 1:
        print "value rm {}".format(value)
        my_trainings.remove(value)
        if value not in my_duplicates:
            print "value add {}".format(value)
            my_duplicates.append(value)

            
print my_trainings
print my_duplicates


value- python
value rm python
value add python
value- django
value rm django
value add django
value- python
value rm python
value- django
value- python
value- devops
['django', 'python', 'devops']
['python', 'django']

In [54]:
# example2
my_days  = ['yesterday','today','tomorrow','dayafter']
# task1:
# output
#  yesterday'   9
#  today        5
#  tomorrow     8
#  dayafter     8

# task2:
# output
# Yesterday
# TOday
# TOMorrow
# DAYAfter

In [55]:
# task1
for value in my_days:
    print value,len(value)


yesterday 9
today 5
tomorrow 8
dayafter 8

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


['yesterday', 'today', 'tomorrow', 'dayafter']
yesterday 0 y  y
today 1 o t to
tomorrow 2 m to tom
dayafter 3 a day daya

In [63]:
print my_days
for value in my_days:
    print value[0:my_days.index(value)]


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

t
to
day

In [66]:
print my_days
for value in my_days:
    print value[0:my_days.index(value) + 1]


['yesterday', 'today', 'tomorrow', 'dayafter']
y
to
tom
daya

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


pyt
pyt
hon
hon
python

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


['yesterday', 'today', 'tomorrow', 'dayafter']
Yesterday
TOday
TOMorrow
DAYAfter

In [69]:
# soft and deep copy
# memory allocaiton happend for lists in python

In [70]:
# variable
a = 1

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


94193735795096
94193735795096

In [73]:
b = 1

In [74]:
print id(b)


94193735795096

In [75]:
b = 2

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


94193735795096
94193735795096
94193735795072
94193735795072

In [77]:
# lists

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


[1, 2, 3] 140363916491808
[1, 2, 3] 140363916491808

In [86]:
# is
print a is b


True

In [87]:
# softcopy - object(memory) can have multiple labels.
# case1: modify one value within my list
a[1] = 30
print a  #  [1,2,3] or [1,30,3]
print b  #  [1,2,3] or [1,30,3]
print a is b


[1, 30, 3]
[1, 30, 3]
True

In [89]:
# case2 : my modify my whole list
a = [20,30,40]
print a # [1,30,3] or [20,30,40]
print b # [1,30,3] or [20,30,40]
print a is b


[20, 30, 40]
[1, 30, 3]
False

In [90]:
# deep copy - each object has its own memory allocation.

In [91]:
c = [20,30,40]
d = c[:]    # one way to create a deep copy.
print c,d
print id(c),id(d)
print c is d


[20, 30, 40] [20, 30, 40]
140363916329400 140363916329184
False

In [92]:
# case1:
c[1]=33
print c
print d


[20, 33, 40]
[20, 30, 40]

In [93]:
# another way to create deepcopy.
import copy
print dir(copy)
print help(copy.deepcopy)

e = copy.deepcopy(c)
print e
print c
print e is c


['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']
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
[20, 33, 40]
[20, 33, 40]
False

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

In [ ]:
# input of number - string - 1,2,3,4,5,6,7,8,9,10
# 2,4,6,8,10

In [6]:
# example1
even=[]
number = raw_input("please enter the number: ")
for value in number.split(','):
    if int(value) % 2 == 0:
       even.append(value)
print ",".join(even)


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

In [9]:
# list comprehnesion on example1
number = raw_input("please enter your number:")
# [ print expression condition]
print ",".join([ value for value in number.split(',') if int(value) % 2 == 0])


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

In [10]:
# example2:
my_string="today is monday"
for value in my_string.split():
    print value


today
is
monday

In [12]:
[ [value,value.capitalize(),value.upper()] for value in my_string.split()]


Out[12]:
[['today', 'Today', 'TODAY'],
 ['is', 'Is', 'IS'],
 ['monday', 'Monday', 'MONDAY']]

In [ ]: