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. |
|
| extend() | Add all elements of a list to another list |
|
| insert() | Insert an item at the defined index |
|
| remove() | Removes an item from the list |
|
| pop() | Removes and returns an element at the given index |
|
| clear() | Removes all items from the list |
|
| index() | Returns the index of the first matched item |
|
| count() | Returns the count of the number of items passed as an argument |
|
| sort() | Sort items in a list in ascending order. for descending order, pass "reverse" set to False in the argument. |
|
| reverse() | Reverse the order of items in the list |
|
| copy() | Returns a copy of the list |
|
| Built-in Functions | ||
| reduce() | Applies a particular function to all of the list elements and only returns the final summation value |
|
| sum() | Sums up the numbers in the list |
|
| 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 |
|
| max() | return maximum element of a given list |
|
| min() | Return minimum element of a given list |
|
| all() | Returns true if all elements of the list are true |
|
| any() | Return true if any element of the list is true. |
|
| len() | Returns length of the list or size of the list |
|
| enumerate() | Returns enumerate object of the list |
|
| 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 |
|
| map() | Returns a list of the results after applying the given function to each item of a given iterable |
|
| lambda() | Function with any number of arguments but only one expression |
|
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 |
|
| count() | Returns the count of the number of items passed as an argument |
|
| Built-in Functions | ||
| all() | Returns true if all elements of the tuple are true |
|
| any() | Return true if any element of the tuple is true |
|
| len() | Returns length of the tuple or size of the tuple |
|
| enumerate() | Returns enumerate object of the tuple |
|
| max() | return maximum element of a given tuple |
|
| min() | return minimum element of a given lituplest |
|
| sum() | Sums up the numbers in the tuple |
|
| sorted() | returns a sorted list from the tuple |
|
| tuple() | Convert an iterable to a tuple. |
|
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. |
|
| remove() | Removes an element from a set. KeyError, if element is not preset. |
|
| clear() | Removes all items from the set |
|
| copy() | Returns a copy of the set |
|
| pop() | Removes and returns last element of the set. |
|
| update() | Updates a set with the union of itself and others |
|
| union() | Returns the union of sets in a new set |
|
| difference() | Returns the difference of two or more sets as a new set |
|
| difference_update() | Removes all elements of another set from this set |
|
| discard() | Removes an element from set if it is a member, no error if it's not. |
|
| intersection() | Returns the intersection of two sets as a new set |
|
| intersection_update() | Updates the set with the intersection of itself and another |
|
| isdisjoint() | Returns True if two sets have a null intersection |
|
| issubset() | Returns True if another set contains this set |
|
| issuperset() | Returns True if this set contains another set |
|
| symmetric_difference() | Returns the symmetric difference of two sets as a new set |
|
| symmetric_difference_update() | Updates a set with the symmetric difference of itself and another |
|
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 |
|
| clear() | Removes all items from the dictionary |
|
| pop() | Removes and returns an element from a dictionary having the given key |
|
| popitem() | Removes and returns the arbitrary key-value pair (as tuple) from the dictionary |
|
| get() | To access a value for a key |
|
| values() | Returns a list of all the values available in a given dictionary |
|
| str() | Produces a printable string representation of a dictionary |
|
| update() | Adds new dictionary's key-values pairs to current dictionary |
|
| setdefault() | If key is not already in dict, sets its value as default value provided. |
|
| keys() | Returns list of dictionary keys |
|
| items() | Returns a list of dictionary (key, value) tuple pairs |
|
| fromkeys() | Create a new dictionary with keys from sequence |
|
| type() | Returns the type of the passed variable |
|
| cmp() | Compares elements of both dict |
|
| len() | Count of key entities of the dictionary elements |
|
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.