Datatypes 1
Datatypes 1
# Numbers
# A] Integers
a=5
b=-5
c=0
print(type(a))
print(type(b))
print(type(c))
# B] Float
a=40.5
b=3.0
print(type(a))
print(type(b))
# Complex Number
a=1+3j
b=0+1j
print(type(a))
print(type(b))
<class 'int'>
<class 'int'>
<class 'int'>
<class 'float'>
<class 'float'>
<class 'complex'>
<class 'complex'>
# Dictionary
# Creating a Dictionary
sammy.update({'Gender': 'Male'})
sammy
{'username': 'sammy-shark',
'online': 'False',
'followers': 987,
'Gender': 'Male'}
mydict = {'george':16,'amber':19}
mydict.values()
dict_values([16, 19])
mydict.keys()
dict_keys(['george', 'amber'])
list(mydict.values())
[16, 19]
list(mydict.values()).index(19)
list(mydict.values())[0]
16
list(mydict.keys()).index('amber')
list(mydict.keys())[1]
{"type":"string"}
# fromkeys() Method
# vowels keys
keys = ['a', 'e', 'i', 'o', 'u']
vowels = dict.fromkeys(keys)
print(vowels)
# vowels keys
keys = {'a', 'e', 'i', 'o', 'u' }
value = {'vowel', 'ggg', 'hh', 'iii', 'kk'}, {'eee'}
vowels = dict.fromkeys(keys, value)
print(vowels)
# vowels keys
keys = {'a', 'e', 'i', 'o', 'u' }
value = [1]
vowels = dict.fromkeys(keys, value)
print(vowels)
{'a': None, 'e': None, 'i': None, 'o': None, 'u': None}
{'e': ({'hh', 'iii', 'kk', 'vowel', 'ggg'}, {'eee'}), 'i': ({'hh',
'iii', 'kk', 'vowel', 'ggg'}, {'eee'}), 'a': ({'hh', 'iii', 'kk',
'vowel', 'ggg'}, {'eee'}), 'o': ({'hh', 'iii', 'kk', 'vowel', 'ggg'},
{'eee'}), 'u': ({'hh', 'iii', 'kk', 'vowel', 'ggg'}, {'eee'})}
{'e': [1], 'i': [1], 'a': [1], 'o': [1], 'u': [1]}
{'e': [1, 10], 'i': [1, 10], 'a': [1, 10], 'o': [1, 10], 'u': [1, 10]}
# Lists from Dictionaries
<zip at 0x7cdd72476e40>
c = list(a)
c
c_dict = dict(c)
----------------------------------------------------------------------
-----
ValueError Traceback (most recent call
last)
/tmp/ipython-input-28-1547595016.py in <cell line: 0>()
----> 1 c_dict = dict(c)
c_dict
----------------------------------------------------------------------
-----
NameError Traceback (most recent call
last)
/tmp/ipython-input-29-3627909165.py in <cell line: 0>()
----> 1 c_dict
# Boolean
a=True
type(a)
bool
b=False
type(b)
bool
c=true
----------------------------------------------------------------------
-----
NameError Traceback (most recent call
last)
/tmp/ipython-input-33-3578504230.py in <cell line: 0>()
----> 1 c=true
d=false
----------------------------------------------------------------------
-----
NameError Traceback (most recent call
last)
/tmp/ipython-input-34-274358359.py in <cell line: 0>()
----> 1 d=false
zero_int = 0
bool(zero_int)
False
pos_int = 1
bool(pos_int)
True
neg_flt = -5.1
bool(neg_flt)
True
# Sets
# Python program to
# demonstrate sets
# Same as {"a", "b", "c"}
myset = set(["a", "b", "c"])
print(myset)
# Creating a Set
people = {"Jay", "Idrish", "Archi"}
print(people)
# Union
# Intersection
set1 = set()
set2 = set()
for i in range(5):
set1.add(i)
for i in range(3,9):
set2.add(i)
set2
{3, 4, 5, 6, 7, 8}
set1
{0, 1, 2, 3, 4}
#Intersection using
# intersection() function
set3 = set1.intersection(set2)
print("Intersection using intersection() function")
print(set3)
# Intersection using
# "&" operator
set3 = set1 & set2
print("\nIntersection using '&' operator")
print(set3)
# Difference
set1 = set()
set2 = set()
for i in range(5):
set1.add(i)
for i in range(3,9):
set2.add(i)
set1
{0, 1, 2, 3, 4}
# Clearing sets
Initial set
{1, 2, 3, 4, 5, 6}
# Frozen Elements
----------------------------------------------------------------------
-----
AttributeError Traceback (most recent call
last)
/tmp/ipython-input-60-2041669252.py in <cell line: 0>()
1 # below line would cause error as
2 # we are trying to add element to a frozen set
----> 3 frozen_set.add("h")
Set1 = {1, 2, 3, 4, 5}
Set2 = {3, 4, 5, 6, 7}
False
False
True
True
# Strings
#Creating a String
# with single Quotes
print("String with the use of Single Quotes: ")
String1 = 'Welcome to the Geeks World'
print(String1)
a='Hello '
b="World"
print(b*3)
WorldWorldWorld
print(a + b)
Hello World
a='Hello '
b=5
print(a + b)
----------------------------------------------------------------------
-----
TypeError Traceback (most recent call
last)
/tmp/ipython-input-77-3864629426.py in <cell line: 0>()
----> 1 print(a + b)
Hello 5
print(len(b))
----------------------------------------------------------------------
-----
TypeError Traceback (most recent call
last)
/tmp/ipython-input-79-1119462569.py in <cell line: 0>()
----> 1 print(len(b))
# Accessing Characters
Initial String:
GeeksForGeeks
# String Slicing
# Creating a String
String1 = "GeeksForGeeks"
print("Initial String: ")
print(String1)
Initial String:
GeeksForGeeks
# Escape Sequencing
# Initial String
String1 = '''I'm\\\a "Geek"'''
print("Initial String with use of Triple Quotes: ")
print(String1)
Escaping Backslashes:
"C:\Python\Geeks\"
# Formatting of Strings
# Formatting of Integers
String1 = "{:b}".format(5)
print("\nBinary representation of 16 is ")
print(String1)
# Formatting of Floats
String1 = "{:e}".format(2)
print("\nExponent representation of 165.6458 is ")
print(String1)
# Rounding off Integers
String1 = "{:.4f}".format(1/2)
print("\none-sixth is : ")
print(String1)
Binary representation of 16 is
101
one-sixth is :
0.5000
# endswith(): Returns true if the string ends with the specified value
txt = "Hello, welcome to my world."
x = txt.endswith(",")
print(x)
#find(): Searches the string for a specified value and returns the
position of where it was found
txt = "Hello, welcome to my world."
x = txt.find("welcome")
print(x)
s.find("o")
# Printing Methods
name="real"
type(name)
print(dir(name))
print(help(float))
print(help(str.isalnum))
class float(object)
| float(x=0, /)
|
| Convert a string or number to a floating point number, if
possible.
|
| Methods defined here:
|
| __abs__(self, /)
| abs(self)
|
| __add__(self, value, /)
| Return self+value.
|
| __bool__(self, /)
| True if self else False
|
| __ceil__(self, /)
| Return the ceiling as an Integral.
|
| __divmod__(self, value, /)
| Return divmod(self, value).
|
| __eq__(self, value, /)
| Return self==value.
|
| __float__(self, /)
| float(self)
|
| __floor__(self, /)
| Return the floor as an Integral.
|
| __floordiv__(self, value, /)
| Return self//value.
|
| __format__(self, format_spec, /)
| Formats the float according to format_spec.
|
| __ge__(self, value, /)
| Return self>=value.
|
| __getattribute__(self, name, /)
| Return getattr(self, name).
|
| __getnewargs__(self, /)
|
| __gt__(self, value, /)
| Return self>value.
|
| __hash__(self, /)
| Return hash(self).
|
| __int__(self, /)
| int(self)
|
| __le__(self, value, /)
| Return self<=value.
|
| __lt__(self, value, /)
| Return self<value.
|
| __mod__(self, value, /)
| Return self%value.
|
| __mul__(self, value, /)
| Return self*value.
|
| __ne__(self, value, /)
| Return self!=value.
|
| __neg__(self, /)
| -self
|
| __pos__(self, /)
| +self
|
| __pow__(self, value, mod=None, /)
| Return pow(self, value, mod).
|
| __radd__(self, value, /)
| Return value+self.
|
| __rdivmod__(self, value, /)
| Return divmod(value, self).
|
| __repr__(self, /)
| Return repr(self).
|
| __rfloordiv__(self, value, /)
| Return value//self.
|
| __rmod__(self, value, /)
| Return value%self.
|
| __rmul__(self, value, /)
| Return value*self.
|
| __round__(self, ndigits=None, /)
| Return the Integral closest to x, rounding half toward even.
|
| When an argument is passed, work like built-in round(x,
ndigits).
|
| __rpow__(self, value, mod=None, /)
| Return pow(value, self, mod).
|
| __rsub__(self, value, /)
| Return value-self.
|
| __rtruediv__(self, value, /)
| Return value/self.
|
| __sub__(self, value, /)
| Return self-value.
|
| __truediv__(self, value, /)
| Return self/value.
|
| __trunc__(self, /)
| Return the Integral closest to x between 0 and x.
|
| as_integer_ratio(self, /)
| Return integer ratio.
|
| Return a pair of integers, whose ratio is exactly equal to the
original float
| and with a positive denominator.
|
| Raise OverflowError on infinities and a ValueError on NaNs.
|
| >>> (10.0).as_integer_ratio()
| (10, 1)
| >>> (0.0).as_integer_ratio()
| (0, 1)
| >>> (-.25).as_integer_ratio()
| (-1, 4)
|
| conjugate(self, /)
| Return self, the complex conjugate of any float.
|
| hex(self, /)
| Return a hexadecimal representation of a floating-point
number.
|
| >>> (-0.1).hex()
| '-0x1.999999999999ap-4'
| >>> 3.14159.hex()
| '0x1.921f9f01b866ep+1'
|
| is_integer(self, /)
| Return True if the float is an integer.
|
|
----------------------------------------------------------------------
| Class methods defined here:
|
| __getformat__(typestr, /)
| You probably don't want to use this function.
|
| typestr
| Must be 'double' or 'float'.
|
| It exists mainly to be used in Python's test suite.
|
| This function returns whichever of 'unknown', 'IEEE, big-
endian' or 'IEEE,
| little-endian' best describes the format of floating point
numbers used by the
| C type named by typestr.
|
| fromhex(string, /)
| Create a floating-point number from a hexadecimal string.
|
| >>> float.fromhex('0x1.ffffp10')
| 2047.984375
| >>> float.fromhex('-0x1p-1074')
| -5e-324
|
|
----------------------------------------------------------------------
| Static methods defined here:
|
| __new__(*args, **kwargs)
| Create and return a new object. See help(type) for accurate
signature.
|
|
----------------------------------------------------------------------
| Data descriptors defined here:
|
| imag
| the imaginary part of a complex number
|
| real
| the real part of a complex number
None
Help on method_descriptor:
None
# List
# List Indexing
names[0]
{"type":"string"}
names[2]
{"type":"string"}
names[-2]
{"type":"string"}
names=['mark','Jhon','july']
names[:]
names[1:2]
['Jhon']
# max(list): This method returns the elements from the list with
maximum value.
list1, list2 = [123, 'xyz', 'zara', 'abc'], [456, 700, 200]
#print ("Max value element : ", max(list1)) #gives error bcoz contain
multiple datatype values
print ("Max value element : ", max(list2))
----------------------------------------------------------------------
-----
TypeError Traceback (most recent call
last)
/tmp/ipython-input-109-3842352214.py in <cell line: 0>()
----> 1 print ("Max value element : ", max(list1))
# min(list): This method returns the elements from the list with
minimum value.
list1, list2 = [123, 'xyz', 'zara', 'abc'], [456, 700, 200]
#print ("min value element : ", min(list1)) #gives error bcoz contain
multiple datatype values
print ("min value element : ", min(list2))
----------------------------------------------------------------------
-----
TypeError Traceback (most recent call
last)
/tmp/ipython-input-113-423028425.py in <cell line: 0>()
1 a = (123, 'xyz', 'zara', 'abc')
----> 2 a[2] = 'tara'
3 a
# List Methods
# Append
fish = ['barracuda','cod','devil ray','eel']
fish.append('flounder')
print(fish)
['barracuda', 'cod', 'devil ray', 'eel', 'flounder']
fish.append('apple')
fish
# Insert
fish.insert(3, 'anchony')
fish
# Extend
more_fish = ['goby','herring','ide']
fish.extend(more_fish)
fish
['barracuda',
'cod',
'devil ray',
'anchony',
'eel',
'flounder',
'apple',
'goby',
'herring',
'ide']
len(fish)
10
# Remove
fish.remove('devil ray')
fish
['barracuda',
'cod',
'anchony',
'eel',
'flounder',
'apple',
'goby',
'herring',
'ide']
# Pop
fish = ['goby','herring','ide']
fish.pop()
{"type":"string"}
fish
['goby', 'herring']
fish.pop(0)
{"type":"string"}
fish
['herring']
# copy
fish = ['goby','herring','ide']
fish_2 = fish.copy()
fish_2
fish
fish.reverse()
fish
# count
fish = ['c', 'b', 'b', 'a', 'z', 'x']
fish.count('a')
# sort
fish.sort()
fish
# Clear
fish.clear()
fish
[]
# Nested List
[1, 2, 3]
M[1]
M[1][0]
5.2
M[1][0]=100
M
# Initialize list
Lst = [50, 70, 30, 20, 90, 10, 50]
# Display list
print(Lst[::])
# Initialize list
Lst = [50, 70, 30, 20, 90, 10, 50]
# Display list
print(Lst[-7::2])
mylist=[0,1,3,5,6,8,7]
mylist
[0, 1, 3, 5, 6, 8, 7]
mylist[1:7:2]
[1, 5, 8]
mylist[1:6]
[1, 3, 5, 6, 8]
mylist[:4]
[0, 1, 3, 5]
mylist[3:]
[5, 6, 8, 7]
# Initialize list
List = [1, 2, 3, 4, 5, 6, 7, 8, 9]
# Show original list
print("\nOriginal List:\n", List)
print("\nSliced Lists: ")
# Display sliced list
print(List[3:9:2])
# Display sliced list
print(List[::2])
# Display sliced list
Original List:
[1, 2, 3, 4, 5, 6, 7, 8, 9]
Sliced Lists:
[4, 6, 8]
[1, 3, 5, 7, 9]
# Initialize list
List = [1, 2, 3, 4, 5, 6, 7, 8, 9]
# Display sliced list
print(List[::-1])
# Display sliced list
print(List[::-3])
# Display sliced list
print(List[:1:-2])
[9, 8, 7, 6, 5, 4, 3, 2, 1]
[9, 6, 3]
[9, 7, 5, 3]
# Initialize list
List = [-999, 'G4G', 1706256, '^_^', 3.1496]
# Show original list
print("\nOriginal List:\n", List)
print("\nSliced Lists: ")
# Display sliced list
print(List[10::2])
# Display sliced list
print(List[1:1:1])
# Display sliced list
print(List[-1:-1:-1])
# Display sliced list
Original List:
[-999, 'G4G', 1706256, '^_^', 3.1496]
Sliced Lists:
[]
[]
[]
# Initialize list
List = [-999, 'G4G', 1706256, 3.1496, '^_^']
# Show original list
print("\nOriginal List:\n", List)
print("\nSliced Lists: ")
# Modified List
List[2:4] = ['Geeks', 'for', 'Geeks', '!']
# Display sliced list
print(List)
Original List:
[-999, 'G4G', 1706256, 3.1496, '^_^']
Sliced Lists:
[-999, 'G4G', 'Geeks', 'for', 'Geeks', '!', '^_^']
# Modified List
List[:5] = []
# Display sliced list
print(List)
['!', '^_^']
# Initialize list
List = [1, 2, 3, 4, 5, 6, 7, 8, 9]
# Show original list
print("\nOriginal List:\n", List)
print("\nSliced Lists: ")
# Creating new List
newList = List[:3]+List[:3]
# Display sliced list
print(newList)
Original List:
[1, 2, 3, 4, 5, 6, 7, 8, 9]
Sliced Lists:
[1, 2, 3, 1, 2, 3]
# Changng existing List
List = List[::2]+List[1::2]
# Display sliced list
print(List)
[1, 3, 5, 7, 9, 2, 4, 6, 8]
nums = [10, 20, 30, 40, 50, 60, 70, 80, 90]
nums[-3:]
# empty list
print(list())
# vowel string
vowel_string = 'aeiou'
print(list(vowel_string))
# vowel tuple
vowel_tuple = ('a', 'e', 'i', 'o', 'u')
print(list(vowel_tuple))
# vowel list
vowel_list = ['a', 'e', 'i', 'o', 'u']
print(list(vowel_list))
[]
['a', 'e', 'i', 'o', 'u']
['a', 'e', 'i', 'o', 'u']
['a', 'e', 'i', 'o', 'u']
# Tuple
#Create a Tuple:
#Empty Tuple
my_tuple = ()
print(my_tuple)
()
(1, 2, 3)
# Tuple with mixed datatypes
my_tuple = (1, "Hello", 3.4)
print(my_tuple)
# Nested tuple
my_tuple = ("mouse", [8, 4, 6], (1, 2, 3))
print(my_tuple)
# Tuple Packing
my_tuple = 3, 4.6, "dog"
print(my_tuple)
type(my_tuple)
tuple
3
4.6
dog
my_tuple = ("hello")
print(type(my_tuple)) # <class 'str'>
# Creating a tuple having one element
my_tuple = ("hello",)
print(type(my_tuple)) # <class 'tuple'>
# Parentheses is optional
my_tuple = "hello",
print(type(my_tuple)) # <class 'tuple'>
<class 'str'>
<class 'tuple'>
<class 'tuple'>
----------------------------------------------------------------------
-----
IndexError Traceback (most recent call
last)
/tmp/ipython-input-179-4094138577.py in <cell line: 0>()
1 # IndexError: list index out of range
----> 2 print(my_tuple[6])
----------------------------------------------------------------------
-----
TypeError Traceback (most recent call
last)
/tmp/ipython-input-180-3893070040.py in <cell line: 0>()
1 # Index must be an integer
2 # TypeError: list indices must be integers, not float
----> 3 my_tuple[2.0]
# nested tuple
n_tuple = ("mouse", [8, 4, 6], (1, 2, 3))
# nested index
print(n_tuple[2][1])
print(n_tuple[0][0])
2
m
#Negative Indexing
# Negative indexing for accessing tuple elements
my_tuple = ('p', 'e', 'r', 'm', 'i', 't')
print(my_tuple[-1])
print(my_tuple[-6])
t
p
#Slicing
# Accessing tuple elements using slicing
my_tuple = ('p','r','o','g','r','a','m','i','z')
# elements 2nd to 4th
print(my_tuple[0:4])
('p', 'r')
('i', 'z')
#Changing a Tuple
# Changing tuple values
my_tuple = (4, 2, 3, "HELLO")
print(my_tuple)
(4, 2, 3, 'HELLO')
my_tuple[1] = 9
----------------------------------------------------------------------
-----
TypeError Traceback (most recent call
last)
/tmp/ipython-input-189-3682142163.py in <cell line: 0>()
----> 1 my_tuple[1] = 9
----------------------------------------------------------------------
-----
TypeError Traceback (most recent call
last)
/tmp/ipython-input-190-3125035515.py in <cell line: 0>()
1 # However, item of mutable element can be changed
----> 2 my_tuple[3][3] = "A" # Output: (4, 2, 3, [9, 5])
3 print(my_tuple)
TypeError: 'str' object does not support item assignment
print(my_tuple)
#Concatenation
# Output: (1, 2, 3, 4, 5, 6)
print((1, 2, 3) + (4,5,6) + (7, 8,9) + ("hello",))
(1, 2, 3, 4, 5, 6, 7, 8, 9, 'hello')
# Repeat
# Output: ('Repeat', 'Repeat', 'Repeat')
print(("Repeat",) * 3)
#Deleting a Tuple
# Deleting tuples
my_tuple = ('p', 'r', 'o', 'g', 'r', 'a', 'm', 'i', 'z')
# can't delete items
del my_tuple[3]
----------------------------------------------------------------------
-----
TypeError Traceback (most recent call
last)
/tmp/ipython-input-196-1479794251.py in <cell line: 0>()
3 my_tuple = ('p', 'r', 'o', 'g', 'r', 'a', 'm', 'i', 'z')
4 # can't delete items
----> 5 del my_tuple[3]
----------------------------------------------------------------------
-----
NameError Traceback (most recent call
last)
/tmp/ipython-input-198-3044170549.py in <cell line: 0>()
1 # Can delete an entire tuple
----> 2 del my_tuple
3 print(my_tuple)
NameError: name 'my_tuple' is not defined
# Tuple Methods
my_tuple = ('a', 'P', 'p', 'l', 'p',)
print(my_tuple.count('P'))
print(my_tuple.index('z'))
----------------------------------------------------------------------
-----
ValueError Traceback (most recent call
last)
/tmp/ipython-input-199-1802420612.py in <cell line: 0>()
2 my_tuple = ('a', 'P', 'p', 'l', 'p',)
3 print(my_tuple.count('P'))
----> 4 print(my_tuple.index('z'))