article

Sunday, May 29, 2016

Python List Example code

Python List Example code
 
#!/usr/bin/python
#list is a mutable sequence data type

list = [ 'abcd', 786 , 2.23, 'john', 70.2 ]
tinylist = [123, 'john']
print list          # Prints complete list
print list[0]       # Prints first element of the list
print list[1:3]     # Prints elements starting from 2nd till 3rd 
print list[2:]      # Prints elements starting from 3rd element
print tinylist * 2  # Prints list two times
print list + tinylist # Prints concatenated lists
#------------------------------------------------------------------
list1 = ['physics', 'chemistry', 1997, 2000];
list2 = [1, 2, 3, 4, 5, 6, 7 ];
print "list1[0]: ", list1[0]
print "list2[1:5]: ", list2[1:5]
#------------------------------------------------------------------
#Updating Lists
list = ['physics', 'chemistry', 1997, 2000];
print "Value available at index 2 : "
print list[2];
list[2] = 2001;
print "New value available at index 2 : "
print list[2];
#------------------------------------------------------------------
colors = ["red", "green", "burnt sienna", "blue"]
print colors
print colors[0:2]
#------------------------------------------------------------------
colors = ["red", "green", "burnt sienna", "blue"]
colors[0] = "burgundy"
colors[3] = "electric indigo"
print colors
#------------------------------------------------------------------
animals = []
animals.append("lion")
animals.append("tiger")
animals.append("frumious Bandersnatch")
print animals
#------------------------------------------------------------------
groceries = "eggs, spam, pop rocks, cheese"
groceryList = groceries.split(", ")
print groceryList
#------------------------------------------------------------------
zero = 1
one = 2
two = [5, 4, 3, 2, 1, 0]
three = "I love Python!"
four = [["P", "y", "t", "h", "o", "n"],["i", "s"],["h", "a", "r","d"]]
five = {"happy":"birthday"}
six = {1, 2, 3, 4, 5, 6, 7, 8, 9, 10}
days = ("Fri", "Sat", "Sun")
x, y, seven = days
print "zero: {}".format(zero == 0)
print "one: {}".format(one > 22)
print "two: {}".format(len(two) == 5)
print "three: {}".format(three[2] == "Python!")
print "four: {}".format(four[0][5] == 'n' and four[0][0] == "P" and four[2][1] == "u")
print "five: {}".format(five.get("fish") == "chips")
print "five: {}".format(len(five) == 3)
print "six: {}".format(len(six & {2,5,7}) == 2)
print "seven: {}".format(seven == "Wed")
#------------------------------------------------------------------
num = [0, 2, 5, 4, 6, 7]
print num[0] # 0
print num[2:] # [5, 4, 6, 7]
print len(num) # 6
print num + [8, 9] # [0, 2, 5, 4, 6, 7, 8, 9]
#------------------------------------------------------------------
numbers = [4, 3, 6, 1, 2, 0, 5 ]
print numbers # [4, 3, 6, 1, 2, 0, 5]
numbers.sort()
print numbers # [0, 1, 2, 3, 4, 5, 6]
numbers.reverse() 
print numbers #  [5, 4, 3, 2, 1, 0]
#------------------------------------------------------------------
numbers = [0, 0, 2, 3, 3, 3, 3]
print "zero is here ",  numbers.count(0), "times"  # zero is here  2 times
print "one is here ",   numbers.count(1), "times" # one is here  0 times
print "two is here ",   numbers.count(2), "time"  # two is here  1 time
print "three is here ", numbers.count(3), "times" # three is here  4 times
#------------------------------------------------------------------
names = []
names.append("Frank")
names.append("Alexis")
names.append("Erika")
names.append("Ludmila")
print names # ['Frank', 'Alexis', 'Erika', 'Ludmila']
names.insert(0, "Adriana")
print names # ['Adriana', 'Frank', 'Alexis', 'Erika', 'Ludmila']
names.remove("Frank")
names.remove("Alexis")
del names[1] 
print names # ['Adriana', 'Ludmila']
del names[0]
print names # ['Ludmila']
#------------------------------------------------------------------
first = [1, 2, 3]
second = [4, 5, 6]
first.extend(second)
print first # [1, 2, 3, 4, 5, 6]
first[0] = 11
first[1] = 22
first[2] = 33
print first # [11, 22, 33, 4, 5, 6]
print first.pop(5) # 6
print first # [11, 22, 33, 4, 5]
#------------------------------------------------------------------
numbers = [0, 1, 2, 3, 3, 4, 5]
print numbers.index(1) # 1
print numbers.index(3) # 3
#------------------------------------------------------------------
set1 = set(['a', 'b', 'c', 'c', 'd'])
set2 = set(['a', 'b', 'x', 'y', 'z'])
print "set1: " , set1 # set1:  set(['a', 'c', 'b', 'd'])
print "set2: " , set2 # set2:  set(['a', 'x', 'b', 'y', 'z'])
print "intersection: ", set1 & set2 # intersection:  set(['a', 'b'])
print "union: ", set1 | set2 # union:  set(['a', 'c', 'b', 'd', 'y', 'x', 'z'])
print "difference: ", set1 - set2 # difference:  set(['c', 'd'])
print "symmetric difference: ", set1 ^ set2 # symmetric difference:  set(['c', 'd', 'y', 'x', 'z'])
#------------------------------------------------------------------
set1 = set([1, 2])
set1.add(3)
set1.add(4)
set2 = set([1, 2, 3, 4, 6, 7, 8])
set2.remove(8)
print set1 # set([1, 2, 3, 4])
print set2 # set([1, 2, 3, 4, 6, 7])
print "Is set1 subset of set2 ? : ", set1.issubset(set2) # Is set1 subset of set2 ? :  True
print "Is set1 superset of set2 ? : ", set1.issuperset(set2) # Is set1 superset of set2 ? :  False
set1.clear()
print set1 # set([])
#------------------------------------------------------------------
words = { 'girl': 'Maedchen', 'house': 'Haus', 'death': 'Tod' }
print words['house'] # Haus
print words.keys() # ['house', 'girl', 'death']
print words.values() # ['Haus', 'Maedchen', 'Tod']
print words.items() # [('house', 'Haus'), ('girl', 'Maedchen'), ('death', 'Tod')]
print words.pop('girl') # Maedchen
print words # {'house': 'Haus', 'death': 'Tod'}
words.clear()
print words # {}
#------------------------------------------------------------------
a = []
b = list()
print a == b # True
print list((1, 2, 3)) # [1, 2, 3]
print list("ZetCode") # ['Z', 'e', 't', 'C', 'o', 'd', 'e']
print list(['Ruby', 'Python', 'Perl']) # ['Ruby', 'Python', 'Perl']
#------------------------------------------------------------------
n1 = [1, 2, 3, 4, 5]
n2 = [3, 4, 5, 6, 7]
print n1 == n2 # False
print n1 + n2 # [1, 2, 3, 4, 5, 3, 4, 5, 6, 7]
print n1 * 3 # [1, 2, 3, 4, 5, 1, 2, 3, 4, 5, 1, 2, 3, 4, 5]
print 2 in n1 # True
print 2 in n2 # False
#------------------------------------------------------------------
n = [1, 2, 3, 4, 5, 6, 7, 8]
print "There are %d items" % len(n) # There are 8 items
print "Maximum is %d" % max(n) # Maximum is 8
print "Minimum is %d" % min(n) # Minimum is 1
print "The sum of values is %d" % sum(n) # The sum of values is 36
#------------------------------------------------------------------
langs = list()
langs.append("Python")
langs.append("Perl")
print langs # ['Python', 'Perl']
langs.insert(0, "PHP")
langs.insert(2, "Lua")
print langs # ['PHP', 'Python', 'Lua', 'Perl']
langs.extend(("JavaScript", "ActionScript"))
print langs # ['PHP', 'Python', 'Lua', 'Perl', 'JavaScript', 'ActionScript']
#------------------------------------------------------------------
#IndexError, TypeError
n = [1, 2, 3, 4, 5]
try:
    n[0] = 10
    n[6] = 60
except IndexError, e:
    print e # list assignment index out of range
#------------------------------------------------------------------
# TypeError
n = [1, 2, 3, 4, 5]
try:
    print n[1]
    print n['2']
except TypeError, e:
    print "Error in file %s" % __file__
    print "Message: %s" % e # Message: list indices must be integers, not str
#------------------------------------------------------------------    
#Removing elements
langs = ["Python", "Ruby", "Perl", "Lua", "JavaScript"]
print langs # ['Python', 'Ruby', 'Perl', 'Lua', 'JavaScript']
langs.pop(3)
langs.pop()
print langs # ['Python', 'Ruby', 'Perl']
langs.remove("Ruby")
print langs # ['Python', 'Perl']
#------------------------------------------------------------------   
#Modifying elements
langs = ["Python", "Ruby", "Perl"]
langs.pop(2)
langs.insert(2, "PHP")
print langs # ['Python', 'Ruby', 'PHP']
langs[2] = "Perl"
print langs # ['Python', 'Ruby', 'Perl']
#------------------------------------------------------------------  
#Indexing list elements
n = [1, 2, 3, 4, 5, 6, 7, 8]
print n[0] # 1
print n[-1] # 8
print n[-2] # 7
print n[3] # 4
print n[5] # 6
#------------------------------------------------------------------ 
n = [1, 2, 3, 4, 1, 2, 3, 1, 2]
print n.index(1) # 0
print n.index(2) # 1
print n.index(1, 1) # 4
print n.index(2, 2) # 5
print n.index(1, 2, 5) # 4
print n.index(3, 4, 8) # 6
#------------------------------------------------------------------ 
#Slicing
n = [1, 2, 3, 4, 5, 6, 7, 8]
print n[1:5] # [2, 3, 4, 5]
print n[:5] # [1, 2, 3, 4, 5]
print n[1:] # [2, 3, 4, 5, 6, 7, 8]
print n[:] # [1, 2, 3, 4, 5, 6, 7, 8]
#------------------------------------------------------------------
basket = { 'oranges': 12, 'pears': 5, 'apples': 4 }
basket['bananas'] = 5
print basket # {'bananas': 5, 'pears': 5, 'oranges': 12, 'apples': 4}
print "There are %d various items in the basket" % len(basket) # There are 4 various items in the basket
print basket['apples'] # 4
basket['apples'] = 8 
print basket['apples'] # 8
print basket.get('oranges', 'undefined') # 8
print basket.get('cherries', 'undefined') # undefined
#------------------------------------------------------------------
domains = { "de": "Germany", "sk": "Slovakia", "hu": "Hungary",
    "us": "United States", "no": "Norway"  }
for key in domains:
    print key
for k in domains:
    print domains[k]
for k, v in domains.items():
    print ": ".join((k, v))
#------------------------------------------------------------------
items = { "coins": 7, "pens": 3, "cups": 2, 
    "bags": 1, "bottles": 4, "books": 5 }
kitems = items.keys()
kitems.sort()
for k in kitems:
    print ": ".join((k, str(items[k]))) # bags: 1 books: 5 bottles: 4 coins: 7 cups: 2 pens: 3
#------------------------------------------------------------------
dict = {'Name': 'Zara', 'Age': 7, 'Class': 'First'};
print "dict['Name']: ", dict['Name'];
print "dict['Age']: ", dict['Age'];

Related Post