Monday, April 3, 2023

Containers in Python

Container is any object that can hold other objects. There are 4 built in containers:

1. List

A list is defined as an ordered, mutable, and heterogeneous collection of objects.

list1=[1,'a',5.6,'Python']   # create

list1[1],  list1[-4:7]    # read

list1[1]=1.2    # reassigning

for i in lst:     #  loop using in

print(i)

for i in range(len(lst)):     # loop on index

  print(lst[i])

new_list=[expression for element in list]   # list comprehension

eg: string="Python"

list3=[i for i in string]         # create

print(list3)    #  gives ['P','y','t','h','o','n']


list1=[1,2,3,4,5,6]

list2=[ i if i%3==0 else -1 for i in list1 ]          # list comprehension with if else (if no else, if part is at the end)

print(list2)


list1.append(17)   # add at end

list1.extend([2,8.0,'l'])   # add >1

list1.insert(2,'a')    #  add at 2nd index



del list1[1:4] #  deleting 2nd to 4th elements

lst.pop()  # delete last element

lst.pop(1)  # delete 1st index element

lst.remove('x')  # delete element's first occurrence


len(lst), min(lst), sum(lst)

list('abc')   # type casting

any(lst),  all(lst)


lst.index('s')   # find     (in can also be used to find)

lst.count('x')     # find

lst.reverse()     # reverses, no sorting

lst.clear()


m_list=[[1,2,3,4],['a','b','c'],[4.5,6.7,1.3]]     #2d list

print(list1+list2)     #   Concatenation

print(list2*3)   # repeats thrice

print('b' not in list2)    #  boolean

lst.copy(),   list(lst)      # copy

lst = [ ]  # empty list

Sort

lst.sort()    #   sorts the list    , available only in list

sorted(lst)    # returns sorted list, original unaffected, method in other containers also

def check(item1, item2):    # comparator method

    return lst(item1) - lst(item2)

from functools import cmp_to_key

sorted(mylist, key=cmp_to_key(check))



2. Tuple

Tuples are ordered and heterogenous, but they are immutable.

tup = ("python", 1.1, 3)      # create

tup = tuple(lst) ,   tup = tuple(str),   tup = (3,)   # create

tup[0], tup[-4:-1]  # access

a, b, c = tup  #  unpacking

Addition to a tuple can be done in 2 ways - by concatenation, or by converting to list and append.

Tuple3 = Tuple1 + Tuple2    #   concatenation. 

No update or reassign can be done on tuple since immutable.

del tup  # delete

tup.index(), tup.count()    # methods to find

len(tup), any(tup), all(tup), max(tup), sorted(tup)   #   functions on tuple  # sorted returns list

Methods that cannot be used for tuples:   append(), insert(), remove(), pop(), clear(), sort(), reverse()

for i in tup:    # loop

tup1=(1,2,3), tup2=(1,2,3), tup1 is tup2    # returns false

tup = ( )   # empty tuple



3. Set

Sets are unique, unordered, heterogenous and mutable. But a set cannot have mutable elements like lists, sets, or dictionaries (Strings and tuples are immutable along with all primitives)

Set = {'A', 'B', 'C', 'D'}     #   create

Set = set(lst), Set = set(tup)    # create

for x in Set:      # loop

We cannot read from set using index.

Set.add('E')     # insert

Set.update(set1)    #   concatenate

Set.update(lst)

set2 = Set.union(set1)  # concatenate with assignment

Set.remove('D')     # delete

Set.discard('D')

Set.pop()    # cannot give index

Set.clear()

del Set


len(Set), all(Set), any(Set), sorted(Set)     # built-in functions

max(Set), sum(Set) for homogeneous 

set2 = Set.intersection(set1)    # common elements

Set.isdisjoint(set1)     # True if no common elements

set2 = Set.difference(set1)     # minus

set2 = Set.symmetric_difference(set1)   # exclude common

set1.issubset(Set) 

set1 = Set.copy()

Cannot use Set={ } for empty set since that becomes a dictionary.

set1={'abab'} gives {'abab'}

set2=set('abab') gives {‘b’, ‘a’}



4. Dictionary

They store values in key-value pairs.  They are ordered (from Python 3.7) with unique keys. They are mutable. But their keys should be immutable.

dic = {'a':1,'b':2,'c':3}   #   create

dic = dict(a = "John", b = 36, c = "Norway")    #      create with equal to and no quotes for keys

dict[lst]    

dic['a'], dic.get('a')      #    access

dic = { }   #  empty dictionary

dic.keys()  ,   dic.values()

dic['a'] = 5      #    add ,  reassign ,   update

dic.pop('a') ,  del dic,  dic.clear() , dic.popitem()    #   delete

for i in  dic:      # loop keys

for x, y in dic.items():

dic.copy(),  dict(dic)    #  copy

Nested dictionary has dictionary as value, accessed as  dict['a']['age']

len(dic), any(dic),  all(dic), sorted(dic)

dic.fromkeys({0,1,2,3,4})    # create None valued dictionary with keys

dic.has_key('a')

dic={x:x*2 for x in ['a','b','c','d','e']}   #    dictionary comprehension

dic = {1: 'Geeks', 2: 'For',

        3: {'A': 'Welcome', 'B': 'To', 'C': 'Geeks'}}     # nested dictionary


No comments: