Featured Post

Keyword to create root window in python

Types of data collection in python - part 1 of python intermediate level notes

 (1)LIST:



Lists are a collection of data types that are ordered and mutable.



1.Storing variables in a list:

In lists, we first create a variable to store the whole list which is in square brackets[],
in which we store string values, integers. etc and store that list in the variable called mylist.

for example: mylist = ["banana""apple""cherry"]


2.Empty lists:

Empty lists are that lists which do not contain any string values, integers or any other elements.

for example: mylist2 = list()

3.Accessing an element from the list:

To access an element from the list we can use integers to access a specific element from that list,
In which 1st number can be accessed by the integer 0 and the second element can be accessed by the integer 1 and so on.
We can also use negative integers to access an element from the last element.


4.Checking for an element or for the number of element: 

To check for an element you can set a if condition : 

for example: 

mylist = ["banana""apple""cherry"]

if "banana" in mylist:
    print("yes")
else:
    print("no")


output = yes

To check for number of elements you can use the function 'len'

for example : 

               mylist = ["banana", "apple", "cherry"]

       print(len(mylist))

output  = 3

5.How to add,remove,reverse,sort.etc elements in the list:

add:

To add an element to the list you can use 'append'.To use append first write the name of your list then type append(the element you want to add)

for example :

mylist.append("lemon")

To add an element at a spcific position you can use 'insert' 

for example: 

mylist.insert(1"blueberry")

remove:

To remove an element use 'pop'.to use pop type the name of your list and type 'pop()'

for example:

mylist.pop()

To remove a specific element from the list use 'remove'.To use remove type the name of your list and then type remove and then type, the element you want to add.

for example: 

mylist.remove("cherry")

To remove all the elements from the list use 'clear()'.

for example: 

mylist.clear()

To reverse the list use 'reverse'. 

for example: mylist.reverse()


other functions:

To arrange the elements in ascending use 'sort'.

for example: 

mylist.sort()

To create new sorted list use 'sorted'.First, make a new list then use 'sorted()' insert the list you want to sort.

for example : 

newlist = sorted()

To add an element multiple times in your list insert the element in square brackets and multiply the number by the number of times you want that element to exist in

the list.

for example: 

mylist = [0* 5

You can also print a list to a specific element.

for example:

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

          a = mylist[1:5]

          print(a)

output = [2,3,4,5]

output = [2, 3, 4, 5]

To skip numbers you can use ':' two times and type the number you want to skip.

for example: 

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

= mylist[::2]

print(a)

output = [1,3,5,7,9]

output = [1, 3, 5, 7, 9]

To make a copy of a list use 'copy'. First, make a list the make another variable then put an equal sign in the variable of the list and the new variable then put '.copy()' in front of the original list.

for example: 

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

list_cpy = mylist.copy()

You can also make a new list that has the function of squaring a number.

for example: 

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

= [i*for i in mylist]

print(mylist)

print(b)

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

[1,4,9,16,25,36]



 (2)TUPLES:

A tuple is created with brackets or without the brackets, the main part is the comma that is what defines tuple. a tuple is a collection of data types. The main difference between tuples and lists is that a tuple can't be changed after it's created.

A Tuple is only recognized if it has a comma in the brackets. Like: mytuple = ("max",)

In tuple just like lists you can check for an element, you can find the number of elements as you would do in the list. All you do in lists like finding index numbers, slicing numbers, etc, and commands for them are the same.

The advantage of the tuple is that its size and the time to create it is less than lists.



1.Storing elements: 

To store an element in tuple we first make a variable and store the elements in () brackets.

for example: 

mytuple  = ("Max"28"Boston"
mytuple2 = "Max"28"Boston"  

2.Converting lists into tuple:

To convert lists into tuple use 'tuple()'.in the variable make a list the insert the list in brackets of 'tuple()'.

for example: 

mytuple = tuple(["Max"28"Boston"])
print(mytuple)

output =  ('Max', 28, 'Boston')

3.Printing elements: 

To print a specific element create another variable and type the name of the variable in which the tuple is stored and then, in the square brackets type the index number of the element

for example: 

mytuple = tuple(["Max"28"Boston"])
print(mytuple)
item = mytuple[2]

print(item)

output  =    ('Max', 28, 'Boston')
                   Boston

To print elements, one by one from the tuple makes a 'for loop'. You can use any variable instead of i.

for example: 

mytuple = tuple(["Max"28"Boston"])
for i in mytuple:
    print(i)

output = Max
               28
               Boston

4.counting element:

If you want to count the element 'p' how many times it has come in the tuple you can use '.count'. Just put the name of the list in which the element is stored and then put '.count' in front of the variable and then in brackets put the element you want to count.

for example: 

my_tuple = ('a','p','p','l','e')
print(my_tuple.count('p'))

output = 2


5.Slicing

To access finite elements from the tuple use colon(:)

for example:

# a[start:stop:step], default step is 1
= (12345678910)
= a[1:3# Note that the last index is not included
print(b)
= a[2:] # until the end
print(b)
= a[:3# from beginning
print(b)
= a[::2# start to end with every second item
print(b)
= a[::-1# reverse tuple
print(b)

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



 (3)DICTIONARY:



Dictionary is a collection of data types that is unordered and mutable and it has key-value pairs which are separated by, each key is related to the value that is given to it if you try to print the key its value will be printed.

':'



1.Creating a dictionary:

Dictionary is created by making a variable and typing the elements in the braces '{}'.
for example: mydict = {"name":"Max""age":28"city":"New York"}

The dictionary can also be created with the dict() function and uses variables to store values.
for example: mydict2 = dict(name="Mary"age=27city="Boston")     

2.Adding or changing an element: 

To add an element to the dictionary type the variable of the dictionary and then in [] brackets in front of the dictionary variable type the element that you want to add and then, store the value you want to give to the variable in [] brackets.

for example:   

mydict = {"name":"Max""age":28"city":"New York"}
print(mydict) 
        
mydict["email"= "max@xyx.com"
print(mydict)

output = mydict = {"name":"Max", "age":28, "city":"New York", 'email':'max@xyz.com'}

3.Deleting elements: 

To delete the elements in a dictionary you can use del,pop,popitem.

for example:  

mydict = {"name":"Max""age":28"city":"New York"'email':'max@xyz.com'}

del mydict["name"]
print(mydict)

output = {'age': 28, 'city': 'New York', 'email': 'max@xyz.com'}

4.Check for keys:

To check for keys we will use the if condition and try-except if we catch an error.

for example: 

mydict = {"name":"Max""age":28"city":"New York"}
# use if.. in
if "name" in mydict:
    print(mydict["name"])

try:
    print(mydict["firstname"])
except KeyError:
    print("No key found")
    
output = Max
              No key found

5.Looping through a dictionary:


To loop through a dictionary you need to apply a "for loop".

for example:
#loop over keys
for key in my_dict:
    print(key, my_dict[key])

#loop over keys
for key in my_dict.keys():
    print(key)

#loop over values
for value in my_dict.values():
    print(value)

#loop over keys and values
for key, value in my_dict.items():
    print(key, value)

output = 
name Max
age 28
city New York
name
age
city
Max
28
New York
name Max
age 28
city New York

6.Accessing elements:

To print an element from the dict type 'print' then type the variable for the list then in square brackets type the key of the value you want to print.

 

To print all keys from the dictionary use key.

for example:   

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

To print all keys from the dictionary use values. 

for examples: 

for values in mydict.values():
    print(value) 

To print all keys and values from dictionary use key, values.

for example:   

for key, value in mydict.item():
    print(key, value)
output = name Max 
      age 28 
      city New York

You can use the index numbers to print values. To print integers from the dictionary.
for example:  

mydict = {39636981}
value = mydict[3]
print(value)

output  = 9 


7.Merging two dictionary: 

To add a new element from fist dictionary to the other make a dictionary, then make second dictionary then add a new element to the, second dictionary then use '.update'

for example:   

# Use the update() method to merge 2 dicts
# existing keys are overwritten, new keys are added
my_dict = {"name":"Max""age":28"email":"max@xyz.com"}
my_dict_2 = dict(name="Lisa"age=27city="Boston")

my_dict.update(my_dict_2)
print(my_dict)

output = {'name': 'Mary, '27', 'email': 'max@xyz.com', 'city': 'Boston'}



 (4)SETS:



A set is a collection of data types that is unordered and mutable and can't be duplicated. A set is also created with '{}' braces just like a dictionary, in which elements are separated by a comma. If an element is double in the set it is only printed once. The command for adding, removing, checking, printing elements one by one is the same as lists, tuples, and dictionary. 

for example:

myset = {12312}
print(myset)

output = {1, 2, 3}


1.Creating a set: 

To create a set you can make a variable and use {} to store the elements, or you can use the class 'set' and enter the elements in the form of a list to make a set.

for example:  

myset = set([123]) or
myset = set("Hellow"

If you want an empty set then use the set. 

for example: myset = set()


2.Adding or removing elements: 

To add an elements to the set use 'add'.

for example:

myset = set()
myset.add(1)
myset.add(2)
print(myset)

output = {1, 2}

To remove the element use 'remove' or 'discard'.

for example:

myset = {123}
myset.remove(3)     

output = {1, 2, 3}


3.Union and interaction of sets: 

To combine two sets use 'union'.

for example:

odds = {13579}
evens = {02468}
primes = {2357}
= odds.union(evens)
print(u)

output = {0, 1, 2, 3, 4, 5, 6, 7, 8, 9}


To take out comman elements out from a set use 'intersection'.

for example:

odds = {13579}
evens = {02468}
primes = {2357}
= odds.intersection(evens)
print(i)

output = set()


To calculate difference between two sets use 'difference'.

for example:

setA = {123456789}
setB = {123101112}
diff = setA.difference(setB)
print(diff)

output = {4, 5, 6, 7, 8, 9}


To print noncommon elements from the set use 'symmetric_difference'.

for example:

setA = {123456789}
setB = {123101112}
diff = setB.symmetric_difference(setA)
print(diff)

output = {4, 5, 6, 7, 8, 9, 10, 11, 12}


To combine two sets with each other use 'update'. 

for example: 

setA = {123456789}
setB = {123101112}
setA.update(setB)
print(setA)

output = {1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12}


To find if two sets are subset of each other use 'issubset'.

for example:

setA = {123456}
setB = {123}
print(setA.issubset(setB))

output = False


To find if a set is a super set of the other use 'issuperset'.

for example:

setA = {123456}
setB = {123}
print(setA.issuperset(setB))

output = True 


To check weather the two sets have common elements or not use 'isdisjoint'.

for example:

setA = {123456}
setB = {123}
print(setA.isdisjoint(setB))

output = False

setA = {123456}
setB = {123}
setC = {78}
print(setA.disjoint(setB))

output = True


To make a copy of a set use 'copy()' or 'set()'

for example: 

setA = {123456}
setB = setA.copy()
setB.add(7)
print(setB)
print(setA)

output = {1, 2, 3, 4, 5, 6, 7}

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


To make a set immutable use 'frozenset', a frozenset can be created with a variable and then storing the frozenset in the varaible. a frozenset is immutable but can do the tasks like union, interaction, etc.

for example:

= frozenset([1234])
a.add(5)
print(a)

output = a.add(5)

AttributeError: 'frozenset' object has no attribute 'add'


 (5)STRINGS:


A string is a collection of data types that are ordered and immutable and are used for text representation.it is created with quotation mark("") or with apostrophe('').


1.Creating a string:  

To create a string make a variable, put the text you want in an apostrophe('') or in the quotation mark("") then store the text with the apostrophe('') or quotation mark("") in the variable you just made.

for example:

my_string = "Hellow world"
print(my_string)

output = Hellow world 

my_string = 'I'am a programmer'
print(my_string)

output = my_string = 'I'am a programmer'

                    ^

SyntaxError: invalid syntax


There is an error because there are three apostrophes. So you should use '\' before the second apostrophe in the text.

for example: 

my_string = 'I\'am a programmer'
print(my_string)

output = I'am a programmer

To put the text in another line use multiple quotation mark("""text""").

for example:

my_string = """Hello 
World"""
print(my_string)

output = Hello 
              World 

2.Accessing characters from the text: 

To access characters from the text you can use the index number of the character. To do this make a variable called char or any other variable you want then store the variable which contains the text along with the index number of the character you want to access in the square brackets.

for example :

my_string = "Hello World"
char = my_string[1]
print(char)

output = e

To access multiple characters put the index number of the character before the first character you want and the index number of the character after the last character you want then store the variable in which the string is with the index number in the []. 

for example:

my_string = "Hello world"
substring = my_string[1:5]  
print(substring)

output = ello


3.Adding strings: 

To add two strings with one another use '+'.

for example: 

greeting = "Hello"
name = "Tom"
sentence = greeting + " " + name
print(sentence)

output = Hello Tom 


4.Converting lower case letters to upper case letter :

To convert lower case letters to upper case letter use 'upper'.

for example: 

my_string = 'Hello World'
print(my_string.upper())

output =  HELLO WORLD

To convert upper case letters to lower case use 'lower'.

for example: 

my_string = 'HELLOW WORLD'
print(my_string.lower())

output = hello world


5.Checking for elements:

To check if any sentence in the variable start with use 'startswith'.

for example:

my_string = 'Hello World'
print(my_string.startswith('H'))

output = True 

To check if any sentence in the the text endswith use 'endswith'.

for example:

my_string = 'Hello World'
print(my_string.endswith('World'))

output = True

To check the index number of a letter in the word use 'find'. If it did not find a letter in the sentence it will print '1'.

for example:

my_string = 'Hello World'
print("Hello".find("o"))

output = 4

To replace a letter in the sentence use 'replace'.

for example:

my_string  = 'Hello World'
print(my_string.replace('World''Universe'))

output = Hello Universe

To find the numbers of words in a sentence use 'len'.

for example:


6.Printing elements : 

To make a string as a list use 'split'.

for example:

my_string = 'how are you doing'
mylist = my_string.split()
print(mylist)

output = ['how', 'are', 'you', 'doing']

To print elements multiple times use '*'.

for example:

my_list = ['a'* 6
print(my_list)

output = ['a','a','a','a','a','a'] 


7.Changing the type of variable: 

To change the type of variable use '%' as the type of variable float, sting, decimal. etc

for example: 

var = 'Tom'
my_string = "the variable is %s" % var
print(my_string)

output = the variable is Tom

Comments