Untitled

Fold the Video

Loading...

Python
List  https://youtu.be/3velNtfn6A0
Tuple
Dictionary
Set
Strings  (16-08)
Collections (17 -08)
Itertools (18-08)
Lambda Functions(19-08)
Exceptions and error(20-08)
Logging (20-08)
JSON (20-08)
Random Numbers (21-08)
Decorators (21-08)
Generators (21-08)
Threading vs Multiprocessing (22-08)
Multithreading (22-08)
Multiprocessing(23-08)
Function arguments(23-08)
* operator(23-08)
Context managers (23-08)

Python Collections (Arrays)

Lists: are just like dynamic sized arrays, declared in other languages (vector in C++ and ArrayList in Java). Lists need not be homogeneous always which makes it the most powerful tool in Python.

Tuple: A Tuple is a collection of Python objects separated by commas. In some ways, a tuple is similar to a list in terms of indexing, nested objects, and repetition but a tuple is immutable, unlike lists that are mutable.

Set: A Set is an unordered collection data type that is iterable, mutable, and has no duplicate elements. Python’s set class represents the mathematical notion of a set.

Dictionary: in Python is an ordered (since Py 3.7) [unordered (Py 3.6 & prior)] collection of data values, used to store data values like a map, which, unlike other Data Types that hold only a single value as an element, Dictionary holds key:value pair. Key-value is provided in the dictionary to make it more optimized.

List, Tuple, Set, and Dictionary are the data structures in python that are used to store and organize the data in an efficient manner.

List

Lists are used to store multiple items in a single variable.

Lists are one of 4 built-in data types in Python used to store collections of data, the other 3 are Tuple, Set, and Dictionary, all with different qualities and usage.

Lists are created using square brackets:

Declaring and printing list

List items are ordered, changeable, and allow duplicate values.

  1. Ordered

When we say that lists are ordered, it means that the items have a defined order, and that order will not change.

If you add new items to a list, the new items will be placed at the end of the list.

2.Changeable

The list is changeable, meaning that we can change, add, and remove items in a list after it has been created.

  1. Allow Duplicates

Since lists are indexed, lists can have items with the same value

Accessing elements of List:

Ouput

Using negative integers

-1 index prints the last element of the list.

-2 index prints the second last item of the list and so on

Iterating over a list

Using a for loop :

Checking if an elemnts is present in list or not

Example 1

Example 2

Finding out number of elements in  a list

The len() function returns the number of items in an object.

When the object is a string, the len() function returns the number of characters in the string.

Syntax

len(object)

Example

Adding items to the list

append()

To add an item to the end of the list, use the append() method

Insert()

To insert a list item at a specified index, use the insert() method.

The insert() method inserts an item at the specified index

Python
Light
mylist  = ["apple","banana","cherry"]
print(mylist)
mylist.insert(1,"orange")
print(mylist)

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

['apple', 'orange', 'banana', 'cherry']

pop()

The pop() method removes the specified index.

Python
Light
mylist  = ["apple","banana","cherry"]
print(mylist)
mylist.pop(1)
print(mylist)

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

['apple', 'cherry']


If you do not specify the index, the pop() method removes the last item.

Python
Light
mylist  = ["apple","banana","cherry"]
print(mylist)
mylist.pop()
print(mylist)

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

['apple', 'banana']


Python
Light
mylist  = ["apple","banana","cherry"]
print(mylist)
item = mylist.pop()
print(item)
print(mylist)

It also returns the last item in the list

cherry

['apple', 'banana']


remove()

The remove() method removes the specified item.

Python
Light
mylist  = ["apple","banana","cherry"]
print(mylist)
mylist.remove("cherry")
print(mylist)

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

['apple', 'banana']


clear()

The clear() method empties the list.

The list still remains, but it has no content.

Python
Light
mylist  = ["apple","banana","cherry"]
print(mylist)
mylist.clear()
print(mylist)

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

[]


reverse()

This function reverses the list

Python
Light
mylist  = ["apple","banana","cherry"]
print(mylist)
mylist.reverse()
print(mylist)

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

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


Sorting the lists

sort()

List objects have a sort() method that will sort the list alphanumerically, ascending, by default

This updates the new list.

ie changes are made in the list.

Python
Light
mylist  = [6,5,3,7,8]
print(mylist)
mylist.sort()
print(mylist)

[6, 5, 3, 7, 8]

[3, 5, 6, 7, 8]


Python
Light
mylist  = ["banana","cherry","apple"]
print(mylist)
mylist.sort()
print(mylist)

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

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


sorted()

This creates a new list instead of making changes to the new one.

Python
Light
mylist  = ["banana","cherry","apple"]
newlist = sorted(mylist)
print(mylist)
print(newlist)

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

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

Observe the difference carefully between sort() and sorted()

we did mylist.sort() in first case whereas we passed mylist as an argument in sorted method

newlist = sorted(mylist)


Printing multiple items in list 

Python
Light
mylist  = ["banana","cherry","apple"] *3
print(mylist)

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


Joining two lists

Using + operator

Python
Light
mylist1 = ["banana","cherry","apple"] 
mylist2 = [1,2,3,4]
mylistnew1 = mylist1+mylist2
print(mylistnew1)
mylistnew2 = mylist2 + mylist1
print(mylistnew2)

['banana', 'cherry', 'apple', 1, 2, 3, 4]

[1, 2, 3, 4, 'banana', 'cherry', 'apple']

Observe that the list put first in addition has elements before the elements of the list put after the + operator


Using append()

Python
Light
mylist1 = ["banana","cherry","apple"] 
mylist2 = [1,2,3,4]
for x in mylist2:
    mylist1.append(x)
print(mylist1)

['banana', 'cherry', 'apple', 1, 2, 3, 4]

By using + operator method we were creating a new list and storing elements of both lists into a new one but here we have stored the elemnts of mylist2 into mylist1


Python
Light
list_org = ["apple","lemon","orange"]
list_cpy = list_org
print(list_cpy)
list_cpy.append("banana")
print(list_cpy)
print(list_org)

['apple', 'lemon', 'orange']

['apple', 'lemon', 'orange', 'banana']

['apple', 'lemon', 'orange', 'banana']

In this example we are cretaing a new list and copying the origianal list into new one.

But if we make changes to the new list they will also be applied to the original one


copy()

By using this method , the above mentioned pronlem is solved

Python
Light
list_org = ["apple","lemon","orange"]
list_cpy = list_org.copy()
print(list_cpy)
list_cpy.append("banana")
print(list_cpy)
print(list_org)

['apple', 'lemon', 'orange']

['apple', 'lemon', 'orange', 'banana']

['apple', 'lemon', 'orange']


list()

Python
Light
list_org = ["apple","lemon","orange"]
list_cpy = list(list_org)
print(list_cpy)
list_cpy.append("banana")
print(list_cpy)
print(list_org)

['apple', 'lemon', 'orange']

['apple', 'lemon', 'orange', 'banana']

['apple', 'lemon', 'orange']


Slicing

Python
Light
mylist = [1,2,3,4,5,6,7,8,9]
a = mylist[1:5]
print(a)
# Here start value is index 1
# It will start from index 1 and slice the elements till index 4
#Note that index 5 written there is actually excluded 
b = mylist[:5]
print(b)
#if we do not write any start index it starts from index zero ie from the beginning of the list
c = mylist[3:]
print(c)
#if we do not write the end index it ends at the last index
d = mylist[::1]
print(d)
#this prints every item from the start till the end
e  = mylist[::2]
print(e)
#this prints every alternate item from start till end
f = mylist[1 : 6 : 2]
print(f)
#this will print every altenate item from index 1 till index 6(excluded)

[2, 3, 4, 5]

[1, 2, 3, 4, 5]

[4, 5, 6, 7, 8, 9]

[1, 2, 3, 4, 5, 6, 7, 8, 9]

[1, 3, 5, 7, 9]

[2, 4, 6]


Intermediate Python-184

Intermediate Python-186

Tuples

Tuples cannot be changed ones created

Ordered

Immutable

Allows duplicate elements

Created using () - paranthesis( they are optional)


Declaring a tuple

Python
Light
mytuple = ("Nishant" ,19,"Nashik")
print(mytuple)

('Nishant', 19, 'Nashik')


Python
Light
mytuple = ("Nishant")
print(type(mytuple))
#When you have only one item in a tuple you need to put a
#,(comma) after that one item.
#This looks odd but that is how you declare a tuple with one item
#otherwise the type of data structure will be considered as
# string

<class 'str'>


Python
Light
mytuple = ("Nishant",)
print(type(mytuple))

<class 'tuple'>


Tuple()

It is also possible to use the tuple() constructor to make a tuple.

Python
Light
mylist = ["Nishant",19,"Nashik"]
mytuple = tuple(mylist)
print(mytuple)

('Nishant', 19, 'Nashik')


Accessing tuple elements

You can access tuple elements by using the index of tuple elements

Python
Light
mytuple = ("Nishant" ,19,"Pune")
print(mytuple[0])
print(mytuple[2])
print(mytuple[1])

Nishant

Pune

19


Using negative indices

Python
Light
mytuple = ("Nishant" ,19,"Pune")
print(mytuple[-1])
print(mytuple[-3])
print(mytuple[-2])

Pune

Nishant

19


Iterating over tuple

Python
Light
mytuple = (1,2,3,4,5)
for x in mytuple:
	print(x)

1

2

3

4

5


Finding if an item exists in the tuple or not

Python
Light
mytuple =(11,56,78,34,67)
if 11 in mytuple:
  print("yes")
else:
  print("no")
if 71 in mytuple:
  print("yes")
else:
  print("no")

yes

no


len()

Python
Light
mytuple = ('a','e','i','o','u')
print(len(mytuple))

5


Getting the index of an item in tuple

Python
Light
mytuple = ('a','e','i','o','u')
print(mytuple.index('i'))
print(mytuple.index('u'))

2

4


Converting a tuple into a list

Python
Light
mytuple = ('a','e','i','o','u')
mylist = list(mytuple)
print(mylist)

['a', 'e', 'i', 'o', 'u']


Slicing

Python
Light
mytuple = (1,2,3,4,5,6,7,8,9)
a = mytuple[1:5]
print(a)
# Here start value is index 1
# It will start from index 1 and slice the elements till index 4
#Note that index 5 written there is actually excluded 
b = mytuple[:5]
print(b)
#if we do not write any start index it starts from index zero ie from the beginning of the tuple
c = mytuple[3:]
print(c)
#if we do not write the end index it ends at the last index
d = mytuple[::1]
print(d)
#this prints every item from the start till the end
e  = mytuple[::2]
print(e)
#this prints every alternate item from start till end
f = mytuple[1 : 6 : 2]
print(f)
#this will print every altenate item from index 1 till index 6(excluded)

(2, 3, 4, 5)

(1, 2, 3, 4, 5)

(4, 5, 6, 7, 8, 9)

(1, 2, 3, 4, 5, 6, 7, 8, 9)

(1, 3, 5, 7, 9)

(2, 4, 6)


Python
Light
mytuple = "Nishant",19,"Pune"
name,age,city = mytuple
print(name)
print(age)
print(city)

Nishant

19

Pune


Python
Light
mytuple = (0,1,2,3,4)
i1,*i2,i3 = mytuple
print(i1)
print(i3)
print(*i2)

0

4

1 2 3


Tuple vs List

  • They are both used to store collection of data
  • They are both heterogeneous data types means that you can store any kind of data type
  • They are both ordered means the order in which you put the items are kept.
  • They are both sequential data types so you can iterate over the items contained.
  • Items of both types can be accessed by an integer index operator, provided in square brackets, [index]

So well, how they differ then?

The key difference between the tuples and lists is that while the tuples are immutable objects the lists are mutable. This means that tuples cannot be changed while the lists can be modified.

Let’s further understand how this effect our code in terms of time and memory efficiency.

As lists are mutable, Python needs to allocate an extra memory block in case there is a need to extend the size of the list object after it is created. In contrary, as tuples are immutable and fixed size, Python allocates just the minimum memory block required for the data.

As a result, tuples are more memory efficient than the lists.

When it comes to the time efficiency, again tuples have a slight advantage over the lists especially when lookup to a value is considered


https://towardsdatascience.com/python-tuples-when-to-use-them-over-lists-75e443f9dcd7#:~:text=key%20takeaways%20are%3B-,The%20key%20difference%20between%20the%20tuples%20and%20lists%20is%20that,memory%20efficient%20than%20the%20lists.


Dictionary

  1. Key-value pairs
  1. Dictionary is ordered for python 3.7 and above
  1. Mutable

Creating a dictionary

Python
Light
mydict = {"name":"Nishant","Age":"19","City":"Nashik"}
print(mydict)

mydict1 = dict(name = "Harshada",Age = 18,City="Nashik")
print(mydict1)

{'name': 'Nishant', 'Age': '19', 'City': 'Nashik'}

{'name': 'Harshada', 'Age': 18, 'City': 'Nashik'}

Accessing items of dictionary

Python
Light
mydict = {"name":"Nishant","Age":"19","City":"Nashik"}
print(mydict)

mydict1 = dict(name = "Harshada",Age = 18,City="Nashik")
print(mydict1)

value = mydict["name"]
print(value)

anothervalue = mydict1["Age"]
print(anothervalue)

{'name': 'Nishant', 'Age': '19', 'City': 'Nashik'}

{'name': 'Harshada', 'Age': 18, 'City': 'Nashik'}

Nishant

18


Accessing elemnts of dictionary and changing the values of keys

Python
Light
mydict = {"name":"Nishant","Age":"19","City":"Nashik"}
print(mydict)

mydict["email"] = "nsihantkshirsagar@gmail.com"
print(mydict)

mydict["email" ] = "abc@xyz.com"
print(mydict)

{'name': 'Nishant', 'Age': '19', 'City': 'Nashik'}

{'name': 'Nishant', 'Age': '19', 'City': 'Nashik', 'email': 'nsihantkshirsagar@gmail.com'}

{'name': 'Nishant', 'Age': '19', 'City': 'Nashik', 'email': 'abc@xyz.com'}


Deleting key value pairs

Python
Light
mydict = {"name":"Nishant","Age":"19","City":"Nashik"}
print(mydict)

del mydict["name"]
print(mydict)

{'name': 'Nishant', 'Age': '19', 'City': 'Nashik'}

{'Age': '19', 'City': 'Nashik'}


pop()

Python
Light
mydict = {"name":"Nishant","Age":"19","City":"Nashik"}
print(mydict)

mydict.pop("Age")
print(mydict)

{'name': 'Nishant', 'Age': '19', 'City': 'Nashik'}

{'name': 'Nishant', 'City': 'Nashik'}


popitem()

Removes the last key value pair from the dictionary

Python
Light
mydict = {"name":"Nishant","Age":"19","City":"Nashik"}
print(mydict)

mydict.popitem()
print(mydict)

{'name': 'Nishant', 'Age': '19', 'City': 'Nashik'}

{'name': 'Nishant', 'Age': '19'}


finding if the given key exists in the dictionary or not

Python
Light
mydict = {"name":"Nishant","Age":"19","City":"Nashik"}
print(mydict)

if "name" in mydict:
    print(mydict["name"])
else:
    print("error")

try:
    print(mydict["Age"])
except:
    print("error")

{'name': 'Nishant', 'Age': '19', 'City': 'Nashik'}

Nishant

19


Looping over values and keys using for loop

Python
Light
mydict = {"name":"Nishant","Age":"19","City":"Nashik"}

for key in mydict.keys():
    print(key)

for value in mydict.values():
    print(value)
   
for key,value in mydict.items():
    print(key,value)

name

Age

City

Nishant

19

Nashik

name Nishant

Age 19

City Nashik


Python
Light
my_dict = {"name" : "Nishant", "age" : 19 ,"city" : "Nashik"}
my_dict_cpy = my_dict
print(my_dict)

my_dict_cpy["email"] = "abc@xyz.com"
print(my_dict_cpy)
print(my_dict)

{'name': 'Nishant', 'age': 19, 'city': 'Nashik'}

{'name': 'Nishant', 'age': 19, 'city': 'Nashik', 'email': 'abc@xyz.com'}

{'name': 'Nishant', 'age': 19, 'city': 'Nashik', 'email': 'abc@xyz.com'}


copy()

Python
Light
my_dict = {"name" : "Nishant", "age" : 19 ,"city" : "Nashik"}
my_dict_cpy = my_dict.copy()
print(my_dict)

my_dict_cpy["email"] = "abc@xyz.com"
print(my_dict_cpy)
print(my_dict)

{'name': 'Nishant', 'age': 19, 'city': 'Nashik'}

{'name': 'Nishant', 'age': 19, 'city': 'Nashik', 'email': 'abc@xyz.com'}

{'name': 'Nishant', 'age': 19, 'city': 'Nashik'}


dict()

Python
Light
my_dict = {"name" : "Nishant", "age" : 19 ,"city" : "Nashik"}
my_dict_cpy = dict(my_dict)
print(my_dict)
my_dict_cpy["email"] = "abc@xyz.com"
print(my_dict_cpy)
print(my_dict)

{'name': 'Nishant', 'age': 19, 'city': 'Nashik'}

{'name': 'Nishant', 'age': 19, 'city': 'Nashik', 'email': 'abc@xyz.com'}

{'name': 'Nishant', 'age': 19, 'city': 'Nashik'}


Merging dictionaries

update()

Python
Light
my_dict = {"name" : "Nishant", "age" : 19 ,"city" : "Nashik"}
mydict_2 = {"name" : "Rahul", "college" : "Mit"}
my_dict.update(mydict_2)
print(my_dict)

{'name': 'Rahul', 'age': 19, 'city': 'Nashik', 'college': 'Mit'}


Set

Python
Light
myset = {1,2,3,4,5}
print(myset)

{1, 2, 3, 4, 5}


Python
Light
myset = set("Hello")
print(myset)

{'e', 'l', 'H', 'o'}


Python
Light
myset ={} 
print(type(myset))
myset1 = set()
print(type(myset1))

<class 'dict'>

<class 'set'>


add() remove() and discard()

Python
Light
myset ={1,2,3,4,5,6} 
print(myset)
myset.add(7)
myset.add(8)
print(myset)
myset.remove(3)
myset.remove(6)
print(myset)
myset.discard(9)
print(myset)

{1, 2, 3, 4, 5, 6}

{1, 2, 3, 4, 5, 6, 7, 8}

{1, 2, 4, 5, 7, 8}

{1, 2, 4, 5, 7, 8}


pop()

Python
Light
myset ={1,2,3,4,5,6} 
print(myset.pop())
print(myset)

1

{2, 3, 4, 5, 6}


union() and intersection()

Python
Light
odds = {1,3,5,7}
evens ={2,4,6,8}
primes = {2,3,5,7}
print(odds.union(evens))
print(odds.union(primes))
print(odds.intersection(evens))
print(odds.intersection(primes))

{1, 2, 3, 4, 5, 6, 7, 8}

{1, 2, 3, 5, 7}

set()

{3, 5, 7}


difference()

Python
Light



setA = {1,2,3,6,7,8,9}
setB = {1,2,3,10,11,12}

print(setA.difference(setB))
print(setB.difference(setA))

{8, 9, 6, 7}

{10, 11, 12}


update()

Python
Light
setA = {1,2,3,6,7,8,9}
setB = {1,2,3,10,11,12}
setA.update(setB)
print(setA)

{1, 2, 3, 6, 7, 8, 9, 10, 11, 12}


intersection_update()

Python
Light
setA = {1,2,3,6,7,8,9}
setB = {1,2,3,10,11,12}
setA.intersection_update(setB)
print(setA)

{1, 2, 3}


difference_update()

Python
Light
setA = {1,2,3,6,7,8,9}
setB = {1,2,3,10,11,12}
setA.difference_update(setB)
print(setA)
setA.symmetric_difference_update(setB)
print(setA)

{6, 7, 8, 9}


symmetric_difference_update()

Python
Light
setA = {1,2,3,6,7,8,9}
setB = {1,2,3,10,11,12}
setA.symmetric_difference_update(setB)
print(setA)

{6, 7, 8, 9, 10, 11, 12}


issubset()  issuperset() and isdisjoint()

Python
Light
setA = {1,2,3,4,5,6}
setB = {1,2,3}
setC = {13,14,15}
print(setA.issubset(setB))
print(setB.issubset(setA))
print(setA.issuperset(setB))
print(setA.isdisjoint(setB))
print(setA.isdisjoint(setC))

False

True

True

False

True


frozenset() - [immutable]

Python
Light
setA = frozenset([1,2,3,4,5])
print(setA)

frozenset({1, 2, 3, 4, 5})


Intermediate Python-423
Intermediate Python-424

Strings

Like many other popular programming languages, strings in Python 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.

Python
Light
my_str = "Hello World"
print(my_str)

Hello World


Accessing character of string

Python
Light
my_str = "Hello World"
char = my_str[4]
print(my_str)
print(char)
char_negative = my_str

Hello World

o


Using n

collections

  • counter
  • namedtuple
  • orderedDict
  • defaultdict
  • deque
Intermediate Python-446
Intermediate Python-447
Intermediate Python-448

Last Updated:

Summarize & share videos seamlessly

Loading...