0% found this document useful (0 votes)
25 views38 pages

Datatypes 1

The document provides an overview of various data types in Python, including numbers (integers, floats, and complex numbers), dictionaries, and sets. It explains how to create, access, update, and delete elements in dictionaries, as well as operations on sets such as union, intersection, and difference. Additionally, it covers methods for manipulating dictionaries and sets, including fromkeys(), clearing sets, and the use of frozen sets.

Uploaded by

aryan98379uy
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
25 views38 pages

Datatypes 1

The document provides an overview of various data types in Python, including numbers (integers, floats, and complex numbers), dictionaries, and sets. It explains how to create, access, update, and delete elements in dictionaries, as well as operations on sets such as union, intersection, and difference. Additionally, it covers methods for manipulating dictionaries and sets, including fromkeys(), clearing sets, and the use of frozen sets.

Uploaded by

aryan98379uy
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 38

# Data Types In Python

# 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

# with Integer Keys


Dict = {1: 'Geeks', 2: 'For', 3: 'Geeks'}
print(Dict)
type(Dict)

# with Mixed keys


Dict = {'Name': 2, 'Name': [1, 2, 3, 4]}
print(Dict)

# Creating an empty Dictionary


Dict = {}
print(Dict)

# with dict() method


Dict = dict({1: 'Geeks', 2: 'For', 3:'Geeks'})
print(Dict)

# with each item as a Pair


Dict = dict([(1, 'Geeks'), (2, 'For')])
print(Dict)

# Creating a Nested Dictionary

Dict = dict({1: 'Geeks', 2: 'For',


3:{'A' : 'Welcome', 'B' : 'To', 'C' : 'Geeks'}})
print(Dict)

{1: 'Geeks', 2: 'For', 3: 'Geeks'}


{'Name': [1, 2, 3, 4]}
{}
{1: 'Geeks', 2: 'For', 3: 'Geeks'}
{1: 'Geeks', 2: 'For'}
{1: 'Geeks', 2: 'For', 3: {'A': 'Welcome', 'B': 'To', 'C': 'Geeks'}}

# Adding elements to a Dictionary

# Adding elements one at a time


Dict[0] = 'Geeks'
Dict[2] = 'For'
Dict[3] = 1
print(Dict)

# Adding set of values to a single Key


Dict['Value_set'] = 2, 3, 4
print(Dict)

# Updating existing Key's Value


Dict[2] = 10
print(Dict)

# Adding Nested Key value to Dictionary


Dict[10] = {'Nested' :{'1' : 'Life', '2' : 'Geeks'}}
print(Dict)

{1: 'Geeks', 2: 'For', 3: 1, 0: 'Geeks'}


{1: 'Geeks', 2: 'For', 3: 1, 0: 'Geeks', 'Value_set': (2, 3, 4)}
{1: 'Geeks', 2: 10, 3: 1, 0: 'Geeks', 'Value_set': (2, 3, 4)}
{1: 'Geeks', 2: 10, 3: 1, 0: 'Geeks', 'Value_set': (2, 3, 4), 10:
{'Nested': {'1': 'Life', '2': 'Geeks'}}}
# Updating Values in dictionary

sammy = {'username': 'sammy-shark', 'online': True, 'followers': 987}


sammy['online'] = 'False'
sammy

{'username': 'sammy-shark', 'online': 'False', 'followers': 987}

sammy.update({'Gender': 'Male'})
sammy

{'username': 'sammy-shark',
'online': 'False',
'followers': 987,
'Gender': 'Male'}

# Accessing elements from a Dictionary

Dict = {1: 'Geeks', 'name': 'For', 3: 'Geeks'}

# accessing a element using key


print("Accessing a element using key:")
print(Dict[1])

# accessing a element using get() method


print("Accessing a element using get:")
print(Dict.get('name'))

# Accessing element of a nested dictionary

Dict = {'Dict1': {1: 'Geeks'},'Dict2': {'Name': 'For'}}


print(Dict['Dict1'])
print(Dict['Dict1'][1])
print(Dict['Dict2']['Name'])

Accessing a element using key:


Geeks
Accessing a element using get:
For
{1: 'Geeks'}
Geeks
For

# Removing Elements from Dictionary

Dict = { 5 : 'Welcome', 6 : 'To', 7 : 'Geeks',


'A' : {1 : 'Geeks', 2 : 'For', 3 : 'Geeks'},
'B' : {1 : 'Geeks', 2 : 'Life'}}
print(Dict)
# Deleting a Key value
del Dict[6]
print("\nDeleting a specific key: ")
print(Dict)

# Deleting a Key from Nested Dictionary


del Dict['B'][1]
print(Dict)

# Deleting a key using pop() method


Dict = {1: 'Geeks', 'name': 'For', 3: 'Geeks'}
pop_ele = Dict.pop('name')
print('\nDictionary after deletion: ' + str(Dict))
print('Value associated to poped key is: ' + str(pop_ele))

# Deleting an arbitrary key using popitem() function


Dict = {1: 'Geeks', 'name': 'For', 3: 'Geeks'}
pop_ele = Dict.popitem()
print("\nDictionary after deletion: " + str(Dict))
print("The arbitrary pair returned is: " + str(pop_ele))

## Deleting entire Dictionary


Dict = {1: 'Geeks', 'name': 'For', 3: 'Geeks'}
Dict.clear()
print(Dict)

{5: 'Welcome', 6: 'To', 7: 'Geeks', 'A': {1: 'Geeks', 2: 'For', 3:


'Geeks'}, 'B': {1: 'Geeks', 2: 'Life'}}

Deleting a specific key:


{5: 'Welcome', 7: 'Geeks', 'A': {1: 'Geeks', 2: 'For', 3: 'Geeks'},
'B': {1: 'Geeks', 2: 'Life'}}
{5: 'Welcome', 7: 'Geeks', 'A': {1: 'Geeks', 2: 'For', 3: 'Geeks'},
'B': {2: 'Life'}}

Dictionary after deletion: {1: 'Geeks', 3: 'Geeks'}


Value associated to poped key is: For

Dictionary after deletion: {1: 'Geeks', 'name': 'For'}


The arbitrary pair returned is: (3, 'Geeks')
{}

# Getting key from the given value:

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)

# updating the value


value.append(10)
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

w = {"house":"Haus", "cat":"", "red":"rot"}


items_view = w.items()
items = list(items_view)
items

[('house', 'Haus'), ('cat', ''), ('red', 'rot')]

# Turn Lists into Dictionaries

dishes = ["pizza", "sauerkraut", "paella", "hamburger"]


countries = ["Italy", "Germany", "Spain", "USA"]
countries1 = ["Italy1", "Germany1", "Spain1", "USA1"]
a= zip(countries, dishes, countries1)
a

<zip at 0x7cdd72476e40>

c = list(a)
c

[('Italy', 'pizza', 'Italy1'),


('Germany', 'sauerkraut', 'Germany1'),
('Spain', 'paella', 'Spain1'),
('USA', 'hamburger', 'USA1')]

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)

ValueError: dictionary update sequence element #0 has length 3; 2 is


required

c_dict

----------------------------------------------------------------------
-----
NameError Traceback (most recent call
last)
/tmp/ipython-input-29-3627909165.py in <cell line: 0>()
----> 1 c_dict

NameError: name 'c_dict' is not defined

dict(zip(countries, dishes)) # second way


{'Italy': 'pizza',
'Germany': 'sauerkraut',
'Spain': 'paella',
'USA': 'hamburger'}

# 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

NameError: name 'true' is not defined

d=false

----------------------------------------------------------------------
-----
NameError Traceback (most recent call
last)
/tmp/ipython-input-34-274358359.py in <cell line: 0>()
----> 1 d=false

NameError: name 'false' is not defined

# Integers and Floats as Booleans

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)

{'c', 'a', 'b'}

# Methods for sets


#Adding elements

# Creating a Set
people = {"Jay", "Idrish", "Archi"}
print(people)

# This will add Daxit in the set


people.add("Daxit")
print(people)

# Adding elements to the set using iterator


for i in range(1, 6):
people.add(i)
print("\nSet after adding element:", end = " ")
print(people)

{'Idrish', 'Jay', 'Archi'}


{'Idrish', 'Jay', 'Archi', 'Daxit'}

Set after adding element: {1, 2, 3, 4, 5, 'Archi', 'Idrish', 'Daxit',


'Jay'}

# Union

people = {"Jay", "Idrish", "Archil"}


vampires = {"Karan", "Arjun"}
dracula = {"Deepanshu", "Raju"}

# Union using union() function


population = people.union(vampires)
print("Union using union() function")
print(population)

# Union using "|" operator


population = people|dracula
print("\nUnion using '|' operator")
print(population)
Union using union() function
{'Idrish', 'Karan', 'Jay', 'Archil', 'Arjun'}

Union using '|' operator


{'Idrish', 'Raju', 'Deepanshu', 'Jay', 'Archil'}

# 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 intersection() function


{3, 4}

# Intersection using
# "&" operator
set3 = set1 & set2
print("\nIntersection using '&' operator")
print(set3)

Intersection using '&' operator


{3, 4}

# 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}

# Difference of two sets


# using difference() function
set3 = set1.difference(set2)
print(" Difference of two sets using difference() function")
print(set3)

Difference of two sets using difference() function


{0, 1, 2}

# Difference of two sets


# using '-' operator
set3 = set1 - set2
print("\nDifference of two sets using '-' operator")
print(set3)

Difference of two sets using '-' operator


{0, 1, 2}

# Clearing sets

# Python program to demonstrate clearing of set


set1 = {1,2,3,4,5,6}
print("Initial set")
print(set1)

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

# This method will remove


# all the elements of the set
set1.clear()
print("\nSet after using clear() function")
print(set1)

Set after using clear() function


set()

# Frozen Elements

# Python program to demonstrate differences


# between normal and frozen set
normal_set = set(["a", "b","c"])
print(normal_set)

{'c', 'a', 'b'}


# A frozen set
frozen_set = frozenset(["e", "f", "g"])
print(frozen_set)

frozenset({'e', 'g', 'f'})

# below line would cause error as


# we are trying to add element to a frozen set
frozen_set.add("h")

----------------------------------------------------------------------
-----
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")

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

# Operators for sets

# Creating two sets


set1 = set()
set2 = set()
# Adding elements to set1
for i in range(1, 6):
set1.add(i)
# Adding elements to set2
for i in range(3, 8):
set2.add(i)
print("Set1 = ", set1)
print("Set2 = ", set2)

Set1 = {1, 2, 3, 4, 5}
Set2 = {3, 4, 5, 6, 7}

# Union of set1 and set2


set3 = set1 | set2# set1.union(set2)
print("Union of Set1 & Set2: Set3 = ", set3)

Union of Set1 & Set2: Set3 = {1, 2, 3, 4, 5, 6, 7}

# Intersection of set1 and set2


set4 = set1 & set2# set1.intersection(set2)
print("Intersection of Set1 & Set2: Set4 = ", set4)
print("\n")

Intersection of Set1 & Set2: Set4 = {3, 4, 5}


# Checking relation between set3 and set4
if set3 >= set4: # set3.issuperset(set4)
print("Set3 is superset of Set4")
elif set3 <= set4: # set3.issubset(set4)
print("Set3 is subset of Set4")
else : # set3 == set4
print("Set3 is same as Set4")

Set3 is superset of Set4

# displaying relation between set4 and set3


if set4 <= set3: # set4.issubset(set3)
print("Set4 is subset of Set3")
print("\n")

Set4 is subset of Set3

# issubset and issuperset i.e. to test whether every element in s is


in t and ,!every element in t is in s.
setx = set(["apple", "mango"])
sety = set(["mango", "orange"])
setz = set(["mango"])

issubset = setx <= sety


print(issubset)
issuperset = setx >= sety
print(issuperset)
issubset = setz <= sety
print(issubset)
issuperset = sety >= setz
print(issuperset)

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)

String with the use of Single Quotes:


Welcome to the Geeks World
# with double Quotes
print("String with the use of Double Quotes:")
String1 = "I'm a Geek"
print(String1)

String with the use of Double Quotes:


I'm a Geek

# with triple Quotes


print("String with the use of Triple Quotes:")
String1 = '''""''""'''
print(String1)

String with the use of Triple Quotes:


""''""

# Quotes allows multiple lines


print("Creating a multiline String: ")
String1 = '''Geeks
For
Life'''
print(String1)

Creating a multiline String:


Geeks
For
Life

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)

TypeError: can only concatenate str (not "int") to str


print(a + str(b)) #Need to typecast b, convert b into string datatype

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))

TypeError: object of type 'int' has no len()

# Accessing Characters

# Python Program to Access


# characters of String
String1 = "GeeksForGeeks"
print("Initial String: ")
print(String1)
# Printing First character
print("\nFirst character of String is: ")
print(String1[0])
# Printing Last character
print("\nLast character of String is: ")
print(String1[-1])

Initial String:
GeeksForGeeks

First character of String is:


G

Last character of String is:


s

# String Slicing

# Creating a String
String1 = "GeeksForGeeks"
print("Initial String: ")
print(String1)

Initial String:
GeeksForGeeks

# Printing 3rd to 12th character


print("Slicing characters from 3-12: ")
print(String1[3:12])
Slicing characters from 3-12:
ksForGeek

# Printing characters between


# 3rd and 2nd last character
print("Slicing characters between " +
"3rd and 2nd last character: ")
String1 = "GeeksForGeeks"
print(String1[3:-2])

Slicing characters between 3rd and 2nd last character:


ksForGee

# Escape Sequencing

# Initial String
String1 = '''I'm\\\a "Geek"'''
print("Initial String with use of Triple Quotes: ")
print(String1)

Initial String with use of Triple Quotes:


I'm\ "Geek"

# Escaping Single Quote


String1 = 'I\'m a "Geek"'
print("\nEscaping Single Quote: ")
print(String1)

Escaping Single Quote:


I'm a "Geek"

# Escaping Doule Quotes


String1 = "I'm a \"Geek\""
print("\nEscaping Double Quotes: ")
print(String1)

Escaping Double Quotes:


I'm a "Geek"

# Printing Paths with the


# use of Escape Sequences
String1 = '''"C:\\Python\\Geeks\\"'''
print("\nEscaping Backslashes: ")
print(String1)

Escaping Backslashes:
"C:\Python\Geeks\"
# Formatting of Strings

# Python Program for


# Formatting of Strings
# Default order
String1 = "{} {} {}".format('Geeks', 'For', 'Life')
print("Print String in default order: ")
print(String1)
# Positional Formatting
String1 = "{1} {0} {2}".format('Geeks', 'For', 'Life')
print("\nPrint String in Positional order: ")
print(String1)
# Keyword Formatting
String1 = "{l} {f} {g}".format(g = 'Geeks', f = 'For', l = 'Life')
print("\nPrint String in order of Keywords: ")
print(String1)

Print String in default order:


Geeks For Life

Print String in Positional order:


For Geeks Life

Print String in order of Keywords:


Life For Geeks

# 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

Exponent representation of 165.6458 is


2.000000e+00

one-sixth is :
0.5000

# Python String Methods


# capitalize(): Converts the first character to upper case
txt = "hello, and welcome to my world."
x = txt.capitalize()
print (x)

# casefold(): Converts string into lower case


txt = "HELLO, And Welcome To My World!"
x = txt.casefold()
print(x)

# center(): Returns a centered string


txt = "banana"
x = txt.center(27)
print(x)

# count(): Returns the number of times a specified value occurs in a


string
txt = "I love apples, apple are APPLE favorite fruit"
x = txt.count("APPLE")
print(x)

# encode(): Returns an encoded version of the string


txt = "VIVIAN LOBO"
x = txt.encode()
print(x)

# endswith(): Returns true if the string ends with the specified value
txt = "Hello, welcome to my world."
x = txt.endswith(",")
print(x)

# expandtabs(): Sets the tab size of the string


txt = "H\te\tl\tl\to"
x = txt.expandtabs(10)
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 = "On the other hand, you hands different fingers."


s.find("hands")

s.find("o")

# format(): Formats specified values in a string


txt = "For only {price:.5f} dollars!"
print(txt.format(price = 49.46436346457))
# index(): Searches the string for a specified value and returns the
position of where it was found
txt = "Hello, welcome to my world."
x = txt.index(" ")
print(x)

# isalnum(): Returns True if all characters in the string are


alphanumeric
txt = "#$%"
x = txt.isalnum()
print(x)

# isalpha(): Returns True if all characters in the string are in the


alphabet
txt = "Company12"
x = txt.isalpha()
print(x)

# isdecimal(): Returns True if all characters in the string are


decimals
txt = "\u0033" #unicode for 3
x = txt.isdecimal()
print(x)

# isdigit(): Returns True if all characters in the string are digits


txt = "50800A00"
x = txt.isdigit()
print(x)

# isidentifier(): Returns True if the string is an identifier


txt = "Demo_A"
x = txt.isidentifier()
print(x)

# islower(): Returns True if all characters in the string are lower


case
txt = "hello World!"
x = txt.islower()
print(x)

# isnumeric(): Returns True if all characters in the string are


numeric
txt = "56554300"
x = txt.isnumeric()
print(x)

# isprintable(): Returns True if all characters in the string are


printable
txt = "Hello! Are you #1?"
x = txt.isprintable()
print(x)

# isspace(): Returns True if all characters in the string are


whitespaces
txt = " "
x = txt.isspace()
print(x)

# istitle(): Returns True if the string follows the rules of a title


txt = "Hello, And Welcome To My World!"
x = txt.istitle()
print(x)

# isupper(): Returns True if all characters in the string are upper


case
txt = "THIS IS NOw!"
x = txt.isupper()
print(x)

# join(): Joins the elements of an iterable to the end of the string


myTuple = ("John", "Peter", "Vicky")
x = ", ".join(myTuple)
print(x)

# ljust(): Returns a left justified version of the string


txt = "banana"
x = txt.ljust(0)
print(x, "is my favorite fruit.")

# lower(): Converts a string into lower case


txt = "Hello my FRIENDS!@#$"
x = txt.lower()
print(x)

# lstrip(): Returns a left trim version of the string


word = " xyz"
word.strip()
word.lstrip()
word.rstrip()
txt = " banana "
x = txt.rstrip()
print("of all fruits", x, "is my favorite")

# split(): Splits the string at the specified separator, and returns a


list
txt = "welcome to the jungle"
x = txt.split()
print(x)
# swapcase(): Swaps cases, lower case becomes upper case and viceversa
txt = "Hello My Name Is PETER"
x = txt.swapcase()
print(x)

# title(): Converts the first character of each word to upper case


txt = "Welcome to my world"
x = txt.title()
print(x)

# translate(): Returns a translated string


#use a dictionary with ascii codes to replace 83 (S) with 80 (P):
mydict = {108: 80}
txt = "Hello SAm!"
print(txt.translate(mydict))

# upper(): Converts a string into upper case


txt = "Hello my friends"
x = txt.upper()
print(x)

# zfill(): Fills the string with a specified number of 0 values at the


beginning
txt = "50"
x = txt.zfill(4)
print(x)

# Printing Methods
name="real"
type(name)
print(dir(name))
print(help(float))
print(help(str.isalnum))

Hello, and welcome to my world.


hello, and welcome to my world!
banana
1
b'VIVIAN LOBO'
False
H e l l o
7
For only 49.46436 dollars!
6
False
False
True
False
True
False
True
True
True
True
False
John, Peter, Vicky
banana is my favorite fruit.
hello my friends!@#$
of all fruits banana is my favorite
['welcome', 'to', 'the', 'jungle']
hELLO mY nAME iS peter
Welcome To My World
HePPo SAm!
HELLO MY FRIENDS
0050
['__add__', '__class__', '__contains__', '__delattr__', '__dir__',
'__doc__', '__eq__', '__format__', '__ge__', '__getattribute__',
'__getitem__', '__getnewargs__', '__getstate__', '__gt__', '__hash__',
'__init__', '__init_subclass__', '__iter__', '__le__', '__len__',
'__lt__', '__mod__', '__mul__', '__ne__', '__new__', '__reduce__',
'__reduce_ex__', '__repr__', '__rmod__', '__rmul__', '__setattr__',
'__sizeof__', '__str__', '__subclasshook__', 'capitalize', 'casefold',
'center', 'count', 'encode', 'endswith', 'expandtabs', 'find',
'format', 'format_map', 'index', 'isalnum', 'isalpha', 'isascii',
'isdecimal', 'isdigit', 'isidentifier', 'islower', 'isnumeric',
'isprintable', 'isspace', 'istitle', 'isupper', 'join', 'ljust',
'lower', 'lstrip', 'maketrans', 'partition', 'removeprefix',
'removesuffix', 'replace', 'rfind', 'rindex', 'rjust', 'rpartition',
'rsplit', 'rstrip', 'split', 'splitlines', 'startswith', 'strip',
'swapcase', 'title', 'translate', 'upper', 'zfill']
Help on class float in module builtins:

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:

isalnum(self, /) unbound builtins.str method


Return True if the string is an alpha-numeric string, False
otherwise.

A string is alpha-numeric if all characters in the string are


alpha-numeric and
there is at least one character in the string.

None

# List

names=[] # Creating empty list


print(names)
[]

names=['mark','Jhon','july'] # Each value seprated by comma


print(names)

['mark', 'Jhon', 'july']

# List Indexing

names[0]

{"type":"string"}

names[2]

{"type":"string"}

names[-2]

{"type":"string"}

names=['mark','Jhon','july']

names[:]

['mark', 'Jhon', 'july']

names[1:2]

['Jhon']

# Built-in List Functions and Methods

# len(list): This method returns the number of elements in the list.


list1, list2 = [123, 'xyz', 'zara'], [456, 'abc']
print ("First list length : ", len(list1))
print ("Second list length : ", len(list2))

# 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))

First list length : 3


Second list length : 2
Max value element : 700

print ("Max value element : ", max(list1))

----------------------------------------------------------------------
-----
TypeError Traceback (most recent call
last)
/tmp/ipython-input-109-3842352214.py in <cell line: 0>()
----> 1 print ("Max value element : ", max(list1))

TypeError: '>' not supported between instances of 'str' and 'int'

# 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))

min value element : 200

# list(seq):This method returns the list.

a = (123, 'xyz', 'zara', 'abc')


b = list(a)
print ("List elements : ", b)

List elements : [123, 'xyz', 'zara', 'abc']

a = [123, 'xyz', 'zara', 'abc']


b = tuple(a)
print ("List elements : ", b)

List elements : (123, 'xyz', 'zara', 'abc')

a = (123, 'xyz', 'zara', 'abc')


a[2] = 'tara'
a

----------------------------------------------------------------------
-----
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

TypeError: 'tuple' object does not support item assignment

# List Methods

# Append
fish = ['barracuda','cod','devil ray','eel']
fish.append('flounder')
print(fish)
['barracuda', 'cod', 'devil ray', 'eel', 'flounder']

fish.append('apple')
fish

['barracuda', 'cod', 'devil ray', 'eel', 'flounder', 'apple']

# Insert

fish.insert(3, 'anchony')
fish

['barracuda', 'cod', 'devil ray', 'anchony', 'eel', 'flounder',


'apple']

# 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']

'devil ray' in fish


False

# 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

['goby', 'herring', 'ide']

fish

['goby', 'herring', 'ide']

fish.reverse()
fish

['ide', 'herring', 'goby']

# count
fish = ['c', 'b', 'b', 'a', 'z', 'x']
fish.count('a')

# sort
fish.sort()
fish

['a', 'b', 'b', 'c', 'x', 'z']

# Clear
fish.clear()
fish
[]

# Nested List

M = [[1, 2, 3],[5.2, 6.3, 'python']]


M[0]

[1, 2, 3]

M[1]

[5.2, 6.3, 'python']

M[1][0]

5.2

M[1][0]=100
M

[[1, 2, 3], [100, 6.3, 'python']]

# Python List Slicing


#<b>Syntax:</b>------------Lst[ Initial : End : IndexJump ]

# 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

[50, 70, 30, 20, 90, 10, 50]


[50, 30, 90, 50]

[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:]

[70, 80, 90]

# Using Negative Step and Reversed List


nums = [10, 20, 30, 40, 50, 60, 70,80,90]
nums[::-1]

[90, 80, 70, 60, 50, 40, 30, 20, 10]

#Create lists from string, tuple, and list

# 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)

()

# Tuple having integers


my_tuple = (1, 2, 3)
print(my_tuple)

(1, 2, 3)
# Tuple with mixed datatypes
my_tuple = (1, "Hello", 3.4)
print(my_tuple)

(1, 'Hello', 3.4)

# Nested tuple
my_tuple = ("mouse", [8, 4, 6], (1, 2, 3))
print(my_tuple)

('mouse', [8, 4, 6], (1, 2, 3))

# Tuple Packing
my_tuple = 3, 4.6, "dog"
print(my_tuple)
type(my_tuple)

(3, 4.6, 'dog')

tuple

# tuple unpacking is also possible


a, b, c = my_tuple
print(a) # 3
print(b) # 4.6
print(c) # dog

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'>

# Access Tuple Elements


# Indexing
# Accessing tuple elements using indexing
my_tuple = ('p','e','r','m','i','t')
print(my_tuple[-1])
print(my_tuple[-3])
t
m

# IndexError: list index out of range


print(my_tuple[6])

----------------------------------------------------------------------
-----
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])

IndexError: tuple index out of range

# Index must be an integer


# TypeError: list indices must be integers, not float
my_tuple[2.0]

----------------------------------------------------------------------
-----
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]

TypeError: tuple indices must be integers or slices, not float

# 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', 'o', 'g')

# elements beginning to 2nd


print(my_tuple[:-7])

('p', 'r')

# elements 8th to end


print(my_tuple[7:])

('i', 'z')

# elements beginning to end


print(my_tuple[:])

('p', 'r', 'o', 'g', 'r', 'a', 'm', '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: 'tuple' object does not support item assignment

# However, item of mutable element can be changed


my_tuple[3][3] = "A" # Output: (4, 2, 3, [9, 5])
print(my_tuple)

----------------------------------------------------------------------
-----
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

# Tuples can be reassigned


my_tuple = ('p', 'r', 'o', 'g', 'r', 'a', 'm', 'i', 'z')

print(my_tuple)

('p', 'r', 'o', 'g', 'r', 'a', 'm', 'i', 'z')

#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)

('Repeat', 'Repeat', 'Repeat')

#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]

TypeError: 'tuple' object doesn't support item deletion

# Can delete an entire tuple


del my_tuple
print(my_tuple)

----------------------------------------------------------------------
-----
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'))

ValueError: tuple.index(x): x not in tuple

You might also like