Python chapter 2 what are the data types in python
Python chapter 2 what are the data types in python
Welcome back!
In this chapter, we are going to learn data types in Python.
Before we start, I want to tell you something that we are going to advance
level from this chapter, so be careful and do practice regularly.
Best Regards from,
Msbtenote :),
Data types in Python:
- Booleans are either True or False.
- Numbers can be integers(1,2),float(2.3,4.3),fractions(1/2,3/2) or even complex numbers.
- Strings are sequences of Unicode characters (e.g., an HTML document)
- Lists are ordered sequences of values.
- Tuples are ordered, immutable sequences of values.
- Sets are unordered bags of values.
- Dictionaries are unordered bags of key-value pairs.
Immutable types
- Strings and tuples are immutable, which means once we create them, we can not change them.
- Lists, sets, and dictionaries are mutable, which means we can add, remove elements from them.
String:
- Strings are amongst the most popular types in Python.
- We can create them simply by enclosing characters in quotes.
- Python treats single quotes the same as double-quotes.
- Creating a string is simple as assigning the value to a variable.
- Python does not support a character type. These are treated as strings of length one, thus also considered a substring.
- To access each character, use the square brackets along with the index. We can access a specific element using an integer index that counts from the front of the sequence(starting at zero).
- Counting backward-We can count from the end of the string using negative numbers also.
- Index out of range-If we try to access an element that does not exist, Python will throw an error!
- Easy traversals-The for loop: Python makes string traversals easy with a for a loop.
- Grabbing slice from a string-The slice operator clips out part of a sequence; it works a lot like a range function but with colons that separate the start and the endpoint.[Syntax- start: end: step]
- Slices-Default values for blanks: If one leaves the "Start" part blank, it assumes you want zero. If one leaves the "end" blank, it assumes you want until the end of the string.
String methods:
- format()-The string format() method formats the given string into the more excellent output in Python.
- Index ()-Returns the index of the substring.
- Count ()-Return occurrences of a substring in a string.
- Find ()-Returns the index of the first occurrence of a substring.
- Is lower()-Checks if all alphabets in the string are in lowercase
- isupper()-Checks if all alphabets in the string are in uppercase.
- Lower ()-Returns a lowercased string.
- Upper ()-Returns an uppercased string.
- Swap case()-Swap uppercase characters to lowercase, vice-versa.
- Capitalize ()-Converts the first character to a capital letter.
- Strip ()-Removes leading characters.
- Strip ()-Removes trailing characters.
- isalnum()-Checks alphanumeric characters.
- Is numeric()-Checks numeric characters.
List:
- A list is a data structure that holds an ordered collection of items, i.e., you can store a sequence of items in a list.
- The List of items should be enclosed in square brackets so that Python understands that you are specifying a list.
- Once you have created a list, you can add, remove or search for items in the List.
- Since we can add and remove items, we say that a list is a mutable data type, i.e., this type can be altered.
How to use a list?
- A list is represented using square brackets [] and is created by providing values separated by ",."
- List allow duplicates values.
- List contains an ordered set of elements. Hence it can be accessed by using an index that starts from zero.
- Index values greater than range, then an error is generated.
- A reverse index is also possible just as a string.
- An empty list can be created in two different ways.
- Elements in the List can be updated since the List is mutable.
- List assignment and equivalence:- List assignment is used to assign all the elements of a list to another list.
- Here, memory is allocated for both objects separately. This is called deep copy.
- Whereas here, the same memory is used. This is called shallow copy.
- List comparison and slicing:- List elements or List as a whole also can be compared.
- List slicing is the same as string slicing.
- List class methods:- Since a list is a class, it has many methods attached. We can check all methods using the help function.
- Operator overloaded and len() function.
- Add a new element to the list-append, extend, insert.
- Aggregate methods- max,min,sum,count,index.
- Delete element from list- del,pop,remove.
- List class methods- Sorting,out-place sorting,in-place sorting.Reverse,out-place reverse,in-place reverse.
a=[1,2,3]
b=a
b[1]=30
print(b)
print(a)
Output=[1, 30, 3]
Output=[1, 30, 3]
a=[1,2,3]
b=list(a)
print(b)
b[1]=10
print(b)
print(a)
Output=[1, 10, 3]
Output=[1, 2, 3]
a=[1,2,3,4,5,6,7,8,9]
a[1:5]
a[:6]
a[3:]
a[2:9:2]
[3, 5, 7, 9]
a=[1,2,3]
x=[2,1,1]
a[1]==x[2]
a==x
a is greater than x
Output=True
List Methods
l1=[1,2,3,4]
print(l1)
Output=[1, 2, 3, 4]
a=[5,6,7,8]
print(a)
Output=[5, 6, 7, 8]
print(b)
b=l1+a
print(b)
Output=[1, 2, 3, 4, 5, 6, 7, 8]
print(c)
c=b*2
print(c)
Output=[1, 2, 3, 4, 5, 6, 7, 8, 1, 2, 3, 4, 5, 6, 7, 8]
print(c)
x=len(c)
print(x)
Output=16
d=[1,2,3,4]
print(d)
Output=[1, 2, 3, 4]
e=[2,4,6,8]
print(e)
Output=[2, 4, 6, 8]
d.append(30)
print(d)
Output=[1, 2, 3, 4, 30]
d.append(e)
print(d)
Output=[1, 2, 3, 4, 30, [2, 4, 6, 8]]
d.extend(e)
print(d)
Output=[1, 2, 3, 4, 30, [2, 4, 6, 8], 2, 4, 6, 8]
d.insert(2,3)
print(d)
d.insert(2,3)
print(d)
Output=[1, 2, 3, 3, 4, 30, [2, 4, 6, 8], 2, 4, 6, 8]
h1=[2,3,4,5]
print(h)
Output=[2, 3, 4, 5]
h2=[1,2,3,4]
print(h1)
Output=[1, 2, 3, 4]
del h1[1]
print(h1)
Output=[2, 4, 5]
del l1
print(l1)
---------------------------------------------------------------------------
NameError Traceback (most recent call last)
in
----> 1 l1
NameError: name 'l1' is not defined
l1=[1,2,3,4]
print(l1)
Output=[1, 2, 3, 4]
x=l1.pop()
print(x)4
print(l1)
Output=[1, 2, 3]
x=l1.pop(2)
print(x)3
print(l1)
Output=[1, 2]
l1.remove(2)
print(l1)
---------------------------------------------------------------------------
ValueError Traceback (most recent call last)
in
----> 1 l1.remove(2)
2 l1
ValueError: list.remove(x): x not in list
del l1
l1=[1,2,3,8,4,5,6,7,8]
print(l)
Output=[1, 2, 3, 8, 4, 5, 6, 7, 8]
max(l1)
Output=8
min(l1)
Output=1
sum(l1)
Output=36
l1.count(8)
Output=1
l1.index(8)
Output=7
l1.index(8,2,5)
Output=3
del l1
del l1
l1=[11,33,55,44,22]
print(l1)
Output=[11,33,55,44,22]
Out place sorting
l2=sorted(l1)
print(l2)
Output=[11, 22, 33, 44, 55]
In place sorting
l1.sort()
print(l1)
Output=[11, 22, 33, 44, 55]
l1.sort(reverse=true) l1
l1.sort(reverse=True)
print(l1)
Output=[55, 44, 33, 22, 11]
del l2
l2=[45,65,78,12]
l3=l2[::-1]
print(l3)
Output=[12, 78, 65, 45]
l2.reverse
print(l2)
Output=[45, 65, 78, 12]
- List membership operation: Since the List is a sequence, we can use a simple loop for selecting each element one by one.
- We can directly check if the element is a part of a given list.
- Nested list-List can have List itself s its element. We can update the element of a list.
- Joining List into string-The join () method returns a string in which a string separator has joined elements of a sequence.
- Splitting strings into list-The split () method returns a list of strings after breaking the given string by the specified separator. If the separator is not provided, then any whitespace is a separator.
- List comprehension-It is used for creating a new list from other iterables.
- Iterables-Is the object capable of returning its member one at a time.
- As list comprehension returns a list, they consist of brackets containing the expression that needs to be executed for each element and the for loop to iterate over each element.
- You can find standard numbers from two lists using for loop.
- Combine the different numbers from the two given lists.
l1 = [2,3,4,5]
l1
[2, 3, 4, 5]
for i in l1:
print(l1)
Output=[2, 3, 4, 5]
[2, 3, 4, 5]
[2, 3, 4, 5]
[2, 3, 4, 5]
x=4
if x in l1:
print(x,"is the element of ",l1)
else:
print(x,"is not the elemnet of",l1)
Output=4 is the element of [2, 3, 4, 5]
del x
x=[[1,2,3,4],[5,6,7,8]]
print(x)
Output=[[1, 2, 3, 4], [5, 6, 7, 8]]
for i in x:
print(i)
for j in i:
print(j)
Output=[1, 2, 3, 4]
1
2
3
4
[5, 6, 7, 8]
5
6
7
8
del y
y=[[[2],[2,3,4],[6,5],[[3],[2,5]]]]
print(y)
Output=[[[2], [2, 3, 4], [6, 5], [[3], [2, 5]]]]
x[0][2]=66
print(x)
Output=[[1, 2, 66, 4], [5, 6, 7, 8]]
Splitting string into list
s="This is a string"
print(s)
Output='This is a string'
l=s.split()
print(l)
Output=['This', 'is', 'a', 'string']
l=s.split(' ',2)
print(l)
Output=['This', 'is', 'a string']
s1="10,20,30,40"
l2=s1.split(",")
print(l2)]
Output=['10', '20', '30', '40']
l3=" ".join(s)
print(l3)
Output='T h i s i s a s t r i n g'
l4='-'.join(s)
print(l4)
Output='T-h-i-s- -i-s- -a- -s-t-r-i-n-g'
del l
del l2
del l3
del l4
l1=[2,3,4,5]
print(l1)
Output=[2, 3, 4, 5]
s1=[]
for n in l1:
s1.append(n**2)
print(s1)
[4, 9, 16, 25]
l1=[2,3,4,5]
s1=[n**2 for n in l1]
print(s1)
Output=[4, 9, 16, 25]
l1=[1,2,3,4]
l2=[2,3,4,5]
print(l1)
Output=[1, 2, 3, 4]
print(l2)
Output=[2, 3, 4, 5]
common_num=[a for a in l1 if a in l2]
print(common_num)
Output=[2, 3, 4]
different_num=[(a,b) for a in l1 for b in l2 if a!=b]
print(different_num)
Output=[(1, 2), (1, 3), (1, 4), (1, 5), (2, 3), (2, 4), (2, 5), (3, 2), (3, 4), (3, 5), (4, 2), (4, 3), (4, 5)]
Tuple
- Tuples are used to hold together multiple objects. Think of them as similar to lists but without the extensive functionality that the list class gives you.
- One prominent feature of tuples is that they are immutable, i.e., you cannot modify tuples.
- Tuples are usually used in cases where a statement or a user-defined function can safely assume that the collection of values, i.e., the tuple of values used, will not change.
Tuple Creation
- Tuples are defined by specifying items separated by commas within an optional pair of parentheses.
- A tuple with only a single element is defined by specifying an item with a comma within an optional pair of parentheses.
Tuple Manipulation
- Tuples are immutable,
- Tuples elements can be accessed by indexing and slicing methods.
Tuples Unpacking
- Unpacking allows assigning multiple values at a time.
- Tuples unpacking is also applicable to loops.
t1=(1,2,3,4)
print(t1)
print(type(t1))
Output=(1, 2, 3, 4)'tuple'>
t2=(2)
print(type(t2))
Output= 'int'>
t3=(2,)
print(type(t3))
Output= 'tuple'>
UNPACKING OF TUPLE
t4=(2,'b',3.4,6,(1,2))
print(type(t4))
Output= 'tuple'>
i1,i2,i3,i4,i5=t4
print(i1,i2,i3,i4,i5)
Output=2 b 3.4 6 (1, 2)
i6,i7=i5
print(i6,i7)
Output=1 2
T1=[(2,3),(4,5),(6,7)]
for x in T1:
print(x)
Output=(2, 3)
(4, 5)
(6, 7)
for x,y in (2,3):
print(x,y)
---------------------------------------------------------------------------
TypeError Traceback (most recent call last)
in
----> 1 for x,y in (2,3):
2 print(x,y)
TypeError: cannot unpack non-iterable int object
for x in t4:
print(x,type(x))
Output=2 'int'>
b 'str'>
3.4 'float'>
6 'int'>
(1, 2) 'tuple'>
x1='b'
x1 in t4
Output=True
x2='a'
x2 in t4
Output=False
a=10
b=20
print(a,b)
Output=10 20
c=a+b
print(c)
Output=30
a=(10,20,30)
b=(40,50,60)
c=a+b
print(c)
Output=(10, 20, 30, 40, 50, 60)
Sets
- A set is an unordered list of elements identified by curly braces.
- It is mutable like List.
- It can only contain unique elements.
- Duplicates are eliminated in the set.
- Set does not support indexing.
Set Class Methods
- Creation method=set(),clear(),add(),update()
- Deletion methods=discard (without error), remove() , pop()
- You can perform boolean operations on sets.
Let's see in our examples:
Sets
x={"VIshal","Pranay","Swapnil"}
print(x)
Output={'Pranay', 'Swapnil', 'VIshal'}
print(type(x))
Output='set'>
cset={11,22,11}
print(cset)
Output={11, 22}
s1=set()
print(s1)
Output=set()
s2=set((2,3,4))
print(type(s2))
s2.clear()
Output= 'set'>
s2.clear
Output=function set.clear>
print(s2)
Output=set()
s1={2,3,4}
print(s1)
Output={2, 3, 4}
s1.add(20)
print(s1)
Output={2, 3, 4, 20}
s1.add(20,30)
print(s1)
---------------------------------------------------------------------------
TypeError Traceback (most recent call last)
in
----> 1 s1.add(20,30)
2 s1
TypeError: add() takes exactly one argument (2 given)
s1.update((20,30))
print(s1)
Output={2, 3, 4, 20, 30}
s1={2,3,4}
s1.discard(2)
print(s1)
Output={3, 4}
s1.discard(20)
print(s1)
Output={3, 4}
s2={2,3,4}
s2.remove(2)
print(s2)
Output={3, 4}
s2.remove(20)
print(s2)
---------------------------------------------------------------------------
KeyError Traceback (most recent call last)
in
----> 1 s2.remove(20)
2 s2
KeyError: 20
s3={2,3,4}
s3.pop()
Output=2
print(s3)
Output={3, 4}
a=set((23,33,33,23,45,67,56,67,45))
print(a)
Output={33, 67, 45, 23, 56}
l=[23,33,33,23,45,67,56,67,45]
a=set(l)
print(a)
Output={33, 67, 45, 23, 56}
Boolean operations on Sets
aset={11,22,33}
bset={12,23,33}
print(aset|bset)
Output={33, 22, 23, 11, 12}
print(aset.union(bset))
Output={33, 22, 23, 11, 12}
#Intersection of Two sets
print(aset&bset)
Output={33}
print(aset.intersection(bset))
Output={33}
#Difference
print(aset-bset)
Output={11, 22}
print(aset.difference(bset))
Output={11, 22}
#SYmetric difference
print(aset^bset)
Output={11, 12, 22, 23}
print(aset.symmetric_difference(bset))
Output={11, 12, 22, 23}
Dictionary
- A dictionary is like an address book where you can find the address or contact details by knowing only their name, i.e., we associate keys (name) with values (details).
- Note that the key must be unique, just like you cannot find out the correct information if you have two persons with the exact same name.
- One can use only immutable objects (like strings) for the keys of a dictionary but can use either immutable or mutable objects for the dictionary's values.
- This basically translates to saying that you should use only simple objects for keys.
- Pairs of keys and values are specified in a dictionary by using the notation
- d = { key1: value1, key2: value2}
- Notice that the key-value pairs are separated by a colon, and the pairs are separated by commas, and all this is enclosed in a pair of curly braces.
- Remember that key-value pairs in a dictionary are not ordered in any manner. If you want a particular order, then you will have to sort them yourself before using it.
- The dictionaries that we will be using are instances/objects of the dict class.
Dictionary Basic Methods
- New key: value pair addition and update of value.
- Keys have to be immutable data types only.
- Basic methods= len(), del(), get(), update() and pop().
You will get this after seeing the example and performing it by
yourself.
Dictionary
d1={}
print(d1)
Output={}
d2=dict()
print(d2)
Output={}
d1={'a':3,'b':4}
print(d1)
Output={'a': 3, 'b': 4}
print(type(d1))
Output='dict'>
d1={3}
print(d1)
print(type(d1))
Output={3}
'set'>
d1=dict([('a',3),('b',4)])
print(type(d1))
print(d1)
Output= 'dict'>
{'a': 3, 'b': 4}
d2=dict([['a',3],['b',4]])
print(type(d2))
print(d2)
Output= 'dict'>
{'a': 3, 'b': 4}
d1={1:'a',2:'b'}
print(d1)
Output={1: 'a', 2: 'b'}
d1[5]='g'
print(d1)
Output={1: 'a', 2: 'b', 5: 'g'}
d1[1]='g'
print(d1)
Output={1: 'g', 2: 'b', 5: 'g'}
d={1:'a',1:'b'}
print(d)
Output={1: 'b'}
d={(1,3):'a',1:'b'}
print(d)
Output={(1, 3): 'a', 1: 'b'}
d={[1,3]:'a',1:'b'}
print(d)
---------------------------------------------------------------------------
TypeError Traceback (most recent call last)
in
----> 1 d={[1,3]:'a',1:'b'}
2 d
TypeError: unhashable type: 'list'
d={1:'a',2:'b'}
print(d)
Output={1: 'a', 2: 'b'}
x=len(d)
print(x)
Output=1
del d
print(d)
---------------------------------------------------------------------------
NameError Traceback (most recent call last)
in
----> 1 d
NameError: name 'd' is not defined
d={1:'a',2:'b'}
print(d)
Output={1: 'a', 2: 'b'}
for i in d:
print(i)
Output=1
2
d.keys()
dict_keys([1, 2])
for i in d.keys():
print(i)
Output=1
2
d.values()
dict_values(['a', 'b'])
for i in d.values():
print(i)
Output=a
b
d.items()
dict_items([(1, 'a'), (2, 'b')])
for i,j in d.items():
print(i,j)
Output=1 a
2 b
d={1:'a',2:'b'}
print(d)
Output={1: 'a', 2: 'b'}
d[1]='c'
print(d)
Output={1: 'c', 2: 'b'}
d={1:'a',2:'b'}
print(d)
Output={1: 'a', 2: 'b'}
d1=d.copy()
print(d1)
Output={1: 'a', 2: 'b'}
d1[1]='c'
print(d1)
Output={1: 'c', 2: 'b'}
print(d)
Output={1: 'a', 2: 'b'}
d={1:'a',2:'b'}
print(d)
Output={1: 'a', 2: 'b'}
print(d.get(1))
Output=a
print(d.get(5))
Output=None
print(d.get(5,'No key'))
print(d)
Output=No key
{1: 'a', 2: 'b'}
d2={3:'c',4:'d'}
print(d2)
Output={3: 'c', 4: 'd'}
d.update(d2)
print(d2)
print(d)
Output={3: 'c', 4: 'd'}
{1: 'a', 2: 'b', 3: 'c', 4: 'd'}
print(d)
Output={2: 'b', 3: 'c', 4: 'd'}
d1={1:'a',2:'b',3:'c'}
print(d1)
Output={1: 'a', 2: 'b', 3: 'c'}
k=d1.pop(1)
print(k)
Output='a'
print(d1)
Output={2: 'b', 3: 'c'}
k=d1.pop(5,'No key')
print(k)
Output='No key'
print(d1)
Output={2: 'b', 3: 'c'}
d={y:y*2 for y in range(5)}
print(d)
Output={0: 0, 1: 2, 2: 4, 3: 6, 4: 8}
x={'a':[4,5,6],'b':(11,22,{'c':9})}
print(x)
Output={'a': [4, 5, 6], 'b': (11, 22, {'c': 9})}
x['a'][1]=55
print(x)
Output={'a': [4, 55, 6], 'b': (11, 22, {'c': 9})}
x['b'][2]['c']=99
print(x)
Output={'a': [4, 55, 6], 'b': (11, 22, {'c': 99})}
In the next chapter, we will start with advanced concepts.
So stay tuned!
Join the conversation