String

  • Strings are arrays of bytes representing Unicode characters
  • However, Python does not have a character data type, a single character is simply a string with a length of 1
  • Square brackets can be used to access elements of the string.

Basic Operations


    ''' string initialization '''
    # using single quote
    s1 = 'Hi. How are you?'
    # using double quote
    s2 = "Hello. How are you?"
    # using triple quote (multi-line)
    s3 = '''How
            are
            your?'''

    ''' accessing characters '''
    # using positive indexing
    print(s1[0])                                                          # H
    # using negative indexing
    print(s1[-2])                                                         # u

    ''' string slicing '''
    # [start:end] -> end not included
    print(s2[1:9])                                                        # ello. Ho
    print(s2[1:-1])                                                       # ello. How are you

    ''' update/delete character or string '''
    # string can be reinitialized or deleted, but characters cannot be updated/deleted
    s2[0] = "Y"                                                           # TypeError: 'str' object does not support item assignment
    del s2[0]                                                             # TypeError: 'str' object does not support item assignment
    s2 = "Yello. How are your?"                                           # works
    del s2                                                                # works

    ''' escape sequence '''
    # escaping same quote as in string initialization
    s4 = 'I\'m a "student"'                                               # I'm a "student"
    # escaping backquotes
    s5 = "C:\\Python\\bin\\"                                              # C:\Python\bin
    # in hex
    s6 = "This is \x47\x65\x65\x6b\x73 in \x48\x45\x58"                   # This is Geeks in HEX
    # raw string to ignore escape sequence
    s7 = r"This is \x47\x65\x65\x6b\x73 in \x48\x45\x58"                  # This is \x47\x65\x65\x6b\x73 in \x48\x45\x58

    ''' string formatting '''
    # default order
    s8 = "{} {} {}".format('abc', 'bcd', 'cde')                           # abc bcd cde
    # positional formatting
    s9 = "{1} {0} {2}".format('abc', 'bcd', 'cde')                        # bcd abc cde
    # keyword formatting
    s10 = "{b} {a} {c}".format(a='abc', b='bcd', c='cde')                 # bcd abc cde

    ''' number formatting '''
    # integer formatting
    s11 = "{0:b}".format(16)                                              # 10000
    i = 12.3456789
    print('%3.2f' % i)                                                    # 12.35
    print('%3.4f' % i)                                                    # 12.3457
    # float formatting
    s12 = "{0:e}".format(165.6458)                                        # 1.656458e+02
    # rounding off integer
    s13 = "{0:.2f}".format(1/6)                                           # 0.17
    # aligning - left, right and center
    s14 = "|{:<10}|{:^10}|{:>10}|".format('abcd', 'abcd', 'abcd')         # |abcd      |   abcd   |      abcd|
        

List

  • similar to dynamically sized arrays, declared in other languages (vector in C++ and ArrayList in Java).
  • A single list may contain DataTypes like Integers, Strings, as well as Objects.
  • Lists are mutable, and hence, they can be altered even after their creation.

Basic Operations


    # initialization
    l1 = [10, "abc", 9.5, ["math", "science", "english"]]                            # [10, 'abc', 9.5, ['math', 'science', 'english']]
    # size of a list using len()
    print(len(l1))                                                                   # 4
    # adding elements to a list using append(element)
    l1.append("A")                                                                   # [10, 'abc', 9.5, ['math', 'science', 'english'], 'A']
    # adding elements to a list using insert(index, element)
    l1.insert(2, "def")                                                              # [10, 'abc', 'def', 9.5, ['math', 'science', 'english'], 'A']
    # adding elements of one list into another using extend(newList)
    l1[4].extend(["economics", "hindi"])                                             # [10, 'abc', 'def', 9.5, ['math', 'science', 'english', 'economics', 'hindi'], 'A']
    # accessing elements using index operator
    print(l1[2])                                                                     # def
    print(l1[-2])                                                                    # ['math', 'science', 'english', 'economics', 'hindi']
    # remove elements using remove(element) - doesn't return the element
    l1.remove("def")                                                                 # [10, 'abc', 9.5, ['math', 'science', 'english', 'economics', 'hindi'], 'A']
    # remove elements using pop(index) - returns the element; index is optional
    l1.pop()                                                                         # [10, 'abc', 9.5, ['math', 'science', 'english', 'economics', 'hindi']]
    l1.pop(3)                                                                        # [10, 'abc', 9.5]
    # slicing a list - [start:end:step] - default values: {start: 0, end: len(list); step: 1}
    l1[1:2]                                                                          # ['abc', 9.5]
    # list comprehension - transforming one list into another
    odd_square = [x ** 2 for x in range(1, 11) if x % 2 == 1]                        # [1, 9, 25, 49, 81]
        

Methods applicable on lists

for

    l1 = [10,5,9,3,7]
    l2 = [10,5,9]
    l3 = [True, True, False]
        
Function Description Example
Built-in Methods
append() Add an element to the end of the list.
l1.append(1) # [10,5,9,3,7,1]
extend() Add all elements of a list to another list
l1.extend([1,2]) # [10,5,9,3,7,1,2]
insert() Insert an item at the defined index
l1.insert(1,8) # [10,8,5,9,3,7]
remove() Removes an item from the list
l1.remove(5) # [10,9,3,7]
pop() Removes and returns an element at the given index
l1.pop(2) # [10,5,3,7]
clear() Removes all items from the list
l1.clear() # []
index() Returns the index of the first matched item
l1.index(10) # 0
count() Returns the count of the number of items passed as an argument
l1.count(10) # 1
sort() Sort items in a list in ascending order. for descending order, pass "reverse" set to False in the argument.
l1.sort() # [3,5,7,9,10]
reverse() Reverse the order of items in the list
l1.reverse() # [7,3,9,5,10]
copy() Returns a copy of the list
l1.copy() # [10,5,9,3,7]
Built-in Functions
reduce() Applies a particular function to all of the list elements and only returns the final summation value
print(functools.reduce(lambda x, y: x+y, l1)) # 34
sum() Sums up the numbers in the list
sum(l1, 0) # 34; 2nd arg: initial value of sum
ord() Returns an integer representing the Unicode code point of the given Unicode character
cmp() Returns 1 if the first list is greater than the second list
cmp(l1, l2) # 1; l1 > l2
max() return maximum element of a given list
max(l1) # 10
min() Return minimum element of a given list
min(l1) # 3
all() Returns true if all elements of the list are true
all(l3) # False
any() Return true if any element of the list is true.
any(l3) # True
len() Returns length of the list or size of the list
len(l1) # 5
enumerate() Returns enumerate object of the list
list(enumerate(l2, 0)) # [(0,10),(1,5),(2,9)]; 2nd arg: initial value of index
accumulate() Applies a particular function to all of the list elements returns a list containing intermediate results
filter() Tests if each element of a list is true or not
filter(lambda x: x % 2 != 0, l1) # [5,9,3,7]
map() Returns a list of the results after applying the given function to each item of a given iterable
map(lambda x: x + x, l1) # [20,10,18,6,14]
lambda() Function with any number of arguments but only one expression
[lambda x=x: x*10 for x in range(1, 6)] # [10,20,30,40,50]

Logical operations of List

  • Python considers empty strings as having a boolean value of the false and non-empty strings as having a boolean value of True.
  • For the and operator if the left value is true, then the right value is checked and returned. If the left value is false, then it is returned
  • For the or operator if the left value is true, then it is returned, otherwise, if the left value is false, then the right value is returned.

Tuple

  • The sequence of values stored in a tuple can be of any type, and they are indexed by integers.
  • tuples are created by placing a sequence of values separated by 'comma' with or without the use of parentheses for grouping the data sequence.
  • Faster as compared to lists.

    ''' initialization '''
    # empty tuple
    t1 = ()
    # non-empty tuple
    t2 = (10, 'abc')
    # tuple with repetition
    t3 = (0,) * 5              # (0,0,0,0,0)

    ''' accessing tuple elements '''
    # using indexing
    t2[0]                      # 10
    # using tuple unpacking
    a, b = t2                  # a = 10, b = 'abc'

    ''' concatenation '''
    # using +
    t4 = t2 + t3               # (10,'abc',0,0,0,0,0)

    ''' slicing '''
    # similar to list, [start,end,step] - default values: {start: 0, end: len(list); step: 1}
    t4[1,4]                    # ('abc',0,0)

    ''' deleting a tuple '''
    del t1
        

Methods applicable on lists

for

    t1 = (10,5,1,1,7,1)
    t2 = (True, True, False)
    l1 = [10,5,1]
        
Function Description Example
Built-in Methods
index() Returns the index of the first matched item
l1.index(1) # 2
count() Returns the count of the number of items passed as an argument
l1.count(1) # 3
Built-in Functions
all() Returns true if all elements of the tuple are true
all(t2) # False
any() Return true if any element of the tuple is true
any(t1) # True
len() Returns length of the tuple or size of the tuple
len(t1) # 6
enumerate() Returns enumerate object of the tuple
max() return maximum element of a given tuple
max(t1) # 10
min() return minimum element of a given lituplest
min(t1) # 1
sum() Sums up the numbers in the tuple
sum(t1, 0) # 25; 2nd arg: initial value of sum
sorted() returns a sorted list from the tuple
sorted(t1, reverse=True) # (10,7,5,1,1,1)
tuple() Convert an iterable to a tuple.
tuple(l1) # (10,5,1)

Set

  • an unordered collection of data type that is iterable, mutable and has no duplicate elements.
  • The major advantage of using a set, as opposed to a list, is that it has a highly optimized method for checking whether a specific element is contained in the set.
  • Lists cannot be added to a set as elements because Lists are not hashable whereas Tuples can be added because tuples are immutable and hence Hashable.

    ''' initialization '''
    # empty set
    set1 = set()
    # using a list
    s1 = set([1, "abc", 9.5])            # {1,'abc',9.5}

    ''' adding elements '''
    # single element using add()
    s1.add(95)                           # {1, 'abc', 9.5, 95}
    s1.add([1,2,3])                      # not allowed
    s1.add((1,2,3))                      # {1, 9.5, (1, 2, 3), 'abc', 95}
    # multiple elements using update()
    s1.update([10, 11])                  # {1, 9.5, 10, (1, 2, 3), 11, 'abc', 95}

    ''' removing elements '''
    # single element using remove() - KeyError, if key doesn't exist
    s1.remove(11)                        # {1, 9.5, 10, (1, 2, 3), 'abc', 95}
    # single element using discard()
    s1.discard(10)                       # {1, 9.5, (1, 2, 3), 'abc', 95}
    # last element (which cannot be determined if set is unordered) using pop() - returns the element popped
    s1.pop()                             # {1, 9.5, (1, 2, 3), 'abc'}
    # remove all elements using clear()
    s1.clear()                           # {}
        

Methods applicable on set

for

    s1 = set([10,5,9,3,7])
    s2 = set([10,11,12])
    s3 = set([10,7,4])
        
Function Description Example
Built-in Methods
add() Add an element to the set.
s1.add(1) # {1,3,5,7,9,10}
remove() Removes an element from a set. KeyError, if element is not preset.
s1.remove(9) # {3,5,7,10}
clear() Removes all items from the set
s1.clear() # {}
copy() Returns a copy of the set
s1.copy() # {3,5,7,9,10}
pop() Removes and returns last element of the set.
s1.pop() # {5,7,9,10}
update() Updates a set with the union of itself and others
s1.update([10,11,12]) # {3,5,7,9,10,11,12}
union() Returns the union of sets in a new set
s1.union(s2) # {3,5,7,9,10,11,12}
difference() Returns the difference of two or more sets as a new set
s1.difference(s2) # {9,3,5,7}
difference_update() Removes all elements of another set from this set
s1.difference_update(s2) # s1 = {3,5,7,9}
discard() Removes an element from set if it is a member, no error if it's not.
s1.discard(10) # [3,5,7,9]
intersection() Returns the intersection of two sets as a new set
s1.intersection(s3) # {10,7}
intersection_update() Updates the set with the intersection of itself and another
s1.append(s3) # s1 = {10,7}
isdisjoint() Returns True if two sets have a null intersection
s1.isdisjoint(s2) # False
issubset() Returns True if another set contains this set
s1.issubset(s2) # False
issuperset() Returns True if this set contains another set
s1.issuperset(s2) # False
symmetric_difference() Returns the symmetric difference of two sets as a new set
s1.symmetric_difference(s2) # {3,5,7,9,11,12}
symmetric_difference_update() Updates a set with the symmetric difference of itself and another
s1.symmetric_difference_update(s2) # s1 = {3,5,7,9,11,12}

Dictionary

  • Dictionary is an unordered collection of data values, which, unlike other Data Types that hold only a single value as an element, Dictionary holds key:value pair.
  • Keys in a dictionary don't allow Polymorphism.
  • Dictionaries have been modified to maintain insertion order with the release of Python 3.7, so they are now ordered collection of data values.

    ''' initialization '''
    # with mixed keys and values
    d1 = {"name": "abc", : "marks": [100, 92, 93], 1: "A"}
    # using dict method
    d2 = dict({1: "hi", 2: "hello"})

    ''' accessing dictionary elements '''
    # using indexing
    d1["name"]                                 # abc
    # using get()
    d1.get("name")                             # abc

    ''' updating/adding key value pairs '''
    d1["name"] = "xyz"                         # {"name": "xyz", "marks": [100, 92, 93], 1: "A"}
    d1["grade"] = "A"                          # {"name": "xyz", "marks": [100, 92, 93], 1: "A", "grade": "A"}

    ''' removing an element from a dict '''
    # using del keyword
    del d1[1]                                  # {"name": "xyz", "marks": [100, 92, 93], "grade": "A"}
    del d1["marks"][0]                         # {"name": "xyz", "marks": [92, 93], "grade": "A"}
    # using pop() method
    ele = d1.pop("grade")                      # ele = "A", d1 = {"name": "xyz", "marks": [92, 93], "grade": "A"}
    # using popitem() method
    item = d1.popitem()                        # item = ("name": "xyz"), d1 = {"marks": [92, 93], "grade": "A"}
    # using clear() method
    d1.clear()                                 # {}
        

Methods applicable on lists

for

    d1 = {'name': 'abc', 'subjects': ['english', 'maths', 'science'], 'grade': 'A'}
    d2 = {'name': 'bcd', 'marks': 95}
        
Function Description Example
Built-in Methods
copy() Returns a shallow copy of the dictionary
d2 = d1.copy() # {'name': 'abc', 'subjects': ['english', 'maths', 'science'], 'grade': 'A'}
clear() Removes all items from the dictionary
d1.clear() # {}
pop() Removes and returns an element from a dictionary having the given key
val = d1.pop("name") # val = 'abc', d1 = {'subjects': ['english', 'maths', 'science'], 'grade': 'A'}
popitem() Removes and returns the arbitrary key-value pair (as tuple) from the dictionary
val = d1.popitem() # val = ('grade', 'A') d1 = {'name': 'abc', 'subjects': ['english', 'maths', 'science']}
get() To access a value for a key
val = d1.get('name') # val = 'abc'
values() Returns a list of all the values available in a given dictionary
d1.values() # ['abc', ['english', 'maths', 'science'], 'A']
str() Produces a printable string representation of a dictionary
str(d1) # "{'name': 'abc', 'subjects': ['english', 'maths', 'science'], 'grade': 'A'}"
update() Adds new dictionary's key-values pairs to current dictionary
d1.update(d2) # {'name': 'bcd', 'subjects': ['english', 'maths', 'science'], 'grade': 'A', 'marks': 95}
setdefault() If key is not already in dict, sets its value as default value provided.
keys() Returns list of dictionary keys
d1.keys() # ['name', 'subjects', 'grade']
items() Returns a list of dictionary (key, value) tuple pairs
d1.items() # [('name', 'abc'), ('subjects', ['english', 'maths', 'science']), ('grade', 'A')]
fromkeys() Create a new dictionary with keys from sequence
dict.fromkeys(["a", "b", "c"]) # {"a": None, "b": None, "c": None}
type() Returns the type of the passed variable
type(d1) # <class 'dict'>
cmp() Compares elements of both dict
len() Count of key entities of the dictionary elements
len(d1) # 3

Array

  • An Array is a collection of items stored at contiguous memory locations.
  • The idea is to store multiple items of the same type together. This makes it easier to calculate the position of each element by simply adding an offset to a base value
  • If you create arrays using the array module, all elements of the array must be of the same type.

    # importing library
    import array as arr

    ''' initialization '''
    a = arr.array('i', [1, 2, 3])                       # i: integer
    b = arr.array('d', [2.5, 3.2, 3.3])                 # d: decimal

    ''' adding elements to an array '''
    # using insert()
    a.insert(1, 4)                                      # [1, 4, 2, 3]
    # using append()
    b.append(4.4)                                       # [2.5, 3.2, 3.3, 4.4]

    ''' accessing elements '''
    # using indexing
    a[0]                                                # 1

    ''' removing elements from the array '''
    # using pop()
    val = a.pop(2)                                      # val = 4, a = [1, 2, 3]

    ''' slicing an array '''
    b[1:3]                                              # array('d', [3.2, 3.3])

    ''' searching an element in an array '''
    b.index(3.2)                                        # 1

    ''' updating elements '''
    b[1] = 5.5                                          # [2.5, 5.5, 3.3, 4.4]

        

Bytes object

  • The bytes() function returns a simple bytes object - It converts objects into bytes objects, or creates empty bytes object of the specified size.