DSA Flashcards
midterms
four collection data types in the Python programming language
LIST, TUPLE, SET, DICTIONARY
4 properties of list
ordered, indexed, mutable (changeable), allow duplicates
which one is used in list ?
list = [1, 3, ‘hello’]
list = {1, 3, ‘hello’}
list = (1; 3 ; ‘hello’)
list = [1; 3 ; ‘hello’]
list = [1, 3, ‘hello’]
The list starts with what index in a forward direction?
index 0
The list starts with what index in a backward direction?
index -1
format in updating elements of list
list[index]= new value
To add an item to the end of the list, use the _____ method
append()
thislist.append(“orange”)
To determine if a specified item is present in a list use the _____
in keyword
if “apple” in thislist:
print(“Yes, ‘apple’ is in the list”)
To add an item at the specified index in a list, use the ____ method:
insert()
listName.insert(1, “orange”)
The ____ removes the specified item in a list
remove() method
listName.remove(“banana”)
The ____ removes the specified index in a list, (or the last item if index is not specified)
pop() method
listName.pop()
The ____ removes the specified index in a list
del keyword
del listName[index]
The _____ empties the list
clear() method
listName.clear()
a collection of objects which ordered and immutable
Tuple
differences between tuples and lists
tuples - unchangeable, uses ( ), more memory efficient
list - changeable, uses [ ], less memory efficient
how to create tuple
tup1 = (‘physics’, ‘chemistry’, 1997, 2000)
tup2 = (1, 2, 3, 4, 5 )
tup3 = “a”, “b”, “c”, “d”
The ____ is written as two parentheses containing nothing
empty tuple
tup1 = ()
To write a tuple containing a single value, you have to include a ______, even though there is only one value
comma
tup1 = (50,);
how are tuple items accessed ?
using their specific
index value
tup[index]
or
count = 0
for i in tuple1:
print(“tuple1[%d] = %d”%(count, i))
count = count+1
Tuples are _____ which means you cannot update or change the values of tuple elements
immutable
you can take _______ to create new tuples
portions of existing tuples
tup3 = tup1 + tup2;
the tuple items ____ be deleted by using the del keyword as tuples are _____
cannot, immutable
To delete
an entire tuple, we can use the_____ with the tuple name.
del keyword
del tuple1
this operator enables a collection elements to be repeated multiple times
repetition
tuple1 * 2
# (1, 2, 3, 4, 1, 2, 3, 4 )
this operator concatinates the collection mentioned on either side of the operator
concatenation
tuple1 + tuple2
operator that returns true if particular item exist in collection, otherwise false
Membership
2 in tuple1
#true or false
used to get the length of collection
length
len(tuple1)
collection of unordered, unindexed, unchangeable, items that do not allow duplicate values
Set
The set can be created by enclosing the comma-separated immutable items with the ____
curly braces { }
the ____ can be used to create the set by the passed sequence
set() method
set4 = set()
Empty curly braces will create a what?
ex:
set3 = {}
dictionary
how to access items in a set?
using a for loop (for x in thisset: ) or using the in keyword (print(“banana” in thisset) )
how to add elements to set
add() method
set.add(“element”)
How many vaules does the set() method can hold?
ex:
Months =
set(“January”,”February”, “March”, “April”, “May”, “June”)
one
it should be Months =
set([“January”,”February”, “March”, “April”, “May”, “June”])
difference between the discard() and remove() method in a set
discard() function if the item does not exist in the set then the set remain unchanged
remove() method will through an error
The _____ empties the set:
clear() method
thisset.clear()
The _____ will delete the set completely
del keyword
del thisset
The union of two sets is calculated by using the ____
using pipe (|) operator:
print(Days1|Days2)
using union() method:
print(Days1.union(Days2))
The intersection of two sets can be performed by the___ or the ____
& operator:
print(Days1&Days2)
intersection() function:
set1.intersection(set2)
The intersection_update() method is different from the intersection() method since it modifies the original set by____
removing the unwanted items
what is the output?
a = {“Devansh”, “bob”, “castle”}
b = {“castle”, “dude”, “emyway”}
c = {“fuson”, “gaurav”, “castle”}
a.intersection_update(b, c)
print(a)
{‘castle’}
# the intersection between a, b, c is the only one retained in a
The difference of two sets can be calculated by using the ___ or ___
subtraction (-) operator :
print(Days1-Days2)
difference() method:
Days1.difference(Days2)
The symmetric dfference of two sets is calculated by_____ or ____.
^ operator :
c = a^b
symmetric_difference() method:
c = a.symmetric_difference(b)
it removes that element which is present in both sets.
Symmetric difference of sets
The ____ is given as the set of the elements that common in both sets
intersection of the two sets
is a collection which is unordered, changeable and indexed.
dictionary
in a dictionary, the keys and values are:
Keys must be a single element
Value can be any type such as list, tuple, integer, etc.
format of a dictionary
dict = {key:value, key:value}
how to call dictionary values
Employee.get(“Age”)
or
print(“Age : %d”%Employee[“Age”])
Adding elements to dictionary one at a time
Dict[0] = ‘Peter’
The items of the dictionary can be deleted by using the ___
del keyword
difference between pop() and popitem()
dict.pop(key)
#removes a specific key
dict.popitem()
#removes last
When looping through a dictionary, the return value are the __ of the dictionary
keys
for loop in dictionary
for loop to print all the keys of a dictionary:
for x in Employee:
print(x)
for loop to print all the values of the dictionary
for x in Employee:
print(Employee[x])
for loop to print the values of the dictionary by using values() method:
for x in Employee.values():
print(x)
for loop to print the items of the dictionary by using items() method:
for x in Employee.items():
print(x)
properties of dict Keys
- cannot store multiple values for the same keys
- last assigned is considered as the value of the key
- key cannot be any mutable object
The ____ statement is used to test as specific condition if it is true
if statement
if condition :
The ____statement is used to test as specific condition if it is false
else statement
else :
it enables us to use if else statements inside an outer if statement
nested if statement
if condition :
if condition:
else:
else
in python, ____ is used to declare a block
indentation
typical number of spaces for indention
4 spaces
if an ‘if clause’ consist of only 1 line, it may go to the ____ as the as the header statement
same line
“if the previous conditions were not true, then try this condition”
elif statement
it enables us to alter the code to repeat in finite number of times
loop / looping
advantages of looping statements
code re-usability
prevent redundancy
we can traverse over the elements of data structures
used when the number of iterations isnt known
while loop
the block of statement is executed until condition specified is satisfied
while loop
other term for while loop
pre-tested loop
used to execute a part of code until given condition is satisfied. Better to use if iteration is known in advance
for loop
other term for for loop
per-tested loop
this statement continues until condition is satisfied
do-while loop
used when executing the loop at least once is necessary (mostly menu driven programs)
do-while loop
other term for do - while loop
post tested loop
one or more loop inside a loop
nested loop
while loop syntax
while condition:
task
it stops the loop even if while condition is true
break
it could stop the current iteration and continue with the next
continue
run a block of code once condition is no longer true
else
ex:
while condition:
task
else :
task
it is the variable that takes the value of item inside the sequence on each iteration
iterating_var
used to iterate over a sequence (list, tuple, string)
for loop
iterating over a sequence is called_____
traversal
it generate a sequence of numbers
range() function
what is the output?
print (list(range (2, 20, 3)))
[2, 5, 8, 11, 14, 17]
what is the output?
print (range (2, 20))
range (2, 20)
what is the output?
print (list(range (2, 5)))
[2, 3, 4]
what is the output?
g = [1, 2, 3, 4, 5]
for i in range(len(g)):
print (“ i skip from”, g[i])
i skip from 1
i skip from 2
i skip from 3
i skip from 4
i skip from 5
heavly used in list of list
nested loops
All syntax in list
list[2] = 10 #assign value in index 2
thislist.append(“orange”) # add item on end
thislist.insert(1, “orange”) # insert item in specified index
thislist.remove(“banana”) # remove specific item
del thislist # remove whole list
thislist.clear() #empties list
all syntax in tuple
tup1 = () # empy tuple
tup[1]= #access of item
tup3 = tup1 + tup2 # combine to create new tuple
tup * 2 # reiterate items twice
item in tup # prints true or false
for i in tup # print all items in tup
len(tup) # length of tup
all syntax in set
s = set() # create empty set
for x in thisset
print(“banana” in thisset) # access item
Months.add (“August”) # adds one item to set
Months.update([“July”,”August”,”September”,”October”]); # multiple
hisset.remove(“banana”) # remove specified item but show error if not found
thisset.discard(“banana”) # remove item but if not found set is unchanged
this.clear() # empties set
del thisset # delete whole set
All syntax in dictionary
dict = {} # empty
dict = dict({key: item})
dict = dict([(key, item),( key, item)])
Employee.get(“Age”) # get value
Employee[“Age”] # get value
Dict[key] = item # add one at a time
del Employee[“Name”] # delete item value
del Employee #delete dictionary
ditct.pop(key) # remove pair and transfer
ditct.popitem() # remove item and transfer
what is python
GDHI:
General Purpose,
Dynamic,
High-Level, and
Interpreted programming language
T or F
Python provides high level data structures
True
T or F
Python does not support Object Oriented Programming
False
T or F
Python is hard and complicated to learn
False
it is simple and easy to learn
Python is ___ than Java
3-5 times shorter
Python’s run time ___ than Java
works harder
T or F
Components can be developed in Java and combined to form applications in Python
True
who developed Python
Guido van Rossum
where is the name Python based from?
BBC comedy series:
Monty Python’s Flying Circus
when was the BBC series aired on?
1970s
qualities that Van Rossum wanted in the name
unique, sort, a little bit mysterious
Python can be used to _____ into Java implementation
prototype components
Python is often ____ shorter than C++
5-10 times
python is a _____ language
glue
T or F
python is used to combine components written in Javascript
False
(C++)
T or F
you can run Python in a GUI environment
True
Python is known for its ____ nature that makes it applicable in almost every domain of ____ development
general-purpose, software
Python is the _____ programming language and can develop any application
fastest-growing
enumerate all the Python applications
Audio or Video-based Applications
Business Applications
Console-based Applications
Desktop GUI Applications
Enterprise Applications
3D CAD Applications
Image Processing applications
Web Applications
Software Development
Scientific and Numeric
3 ways to run a python program
Interactive Interpreter Prompt (IIP)
Script File (SF)
Integrated Development Environment (IDE)
execute the python statement one by one
Interactive Interpreter Prompt (IIP)
used when we are concerned with the output of each line
Interactive Interpreter Prompt (IIP)
steps in opening the Interpreter mode
1.) open terminal (command Prompt)
2.) type python
3.) start coding line by line
it writes multiple lines of code into a file which can be executed later
Script file
steps in Script mode programming
1.) open text editor (notepad)
2.) create file
3.) save file with the .py extension
4.) open command line
5.)navigate to file directory and run
first unix IDE for Python
IDLE
first window interface for python which is an IDE with a ____
PythonWin, GUI
Macintosh version of python
IDLE IDE and Python
(downloadable as MacBinary and BinHex’d file)
a name used to identify a variable, function, class module, or other object
Python Identifier
what do identifiers start?
A-Z
a-z
_ (underscore)
Class Identifiers
uppercase letters (A-Z)
other identifiers
lowercase (a-z)
What is not allowed in Identifiers
Starting with numbers
Special characters as variable names ($, @, %)
how to signify that an identifier is private
single leading underscore (_)
Python reserved keywords
and, assert, break, class, continue, def, del, elif, else, except, exec, finally, for, from, global, if, import, in, is, lambda, not, or, pass, print, raise, return, try, while, with, yield
how are blocks of code denoted in Python
line indention/ indention
line continuation character
\
it allows the line to continue even if they are not on the same line
line continuation character
What statements do not need the use of line continuation character
statements with [], {}, or ()
what is the use of a single and double quote (‘ and “)
used to denote string literals
what is the use of a triple quote ( ‘’’ )
span the string across multiple lines
used to make a next line
\n
It signifies a comment
Hash sign (#)
It signifies a multiline comment
triple quote ( ‘’’ )
These are containers for storing data values
variables
Python has ___ in declaring a variable
no command
The ______ is used to output a variable
print statement
Different data types categories in python
Text type: str
Numeric type: int, float, complex
Sequence type: list, tuple, range
Mapping type: dict
Set Types: set, frozenset
Boolean type: bool
Binary types: bytes, bytearray, memoryview
used to get the datatype of any object
type () function
what type of data type is this:
x = ‘Hello’
str
what type of data type is this:
x = 20
int
what type of data type is this:
x = 20.5
float
what type of data type is this:
x = 2j
complex
what type of data type is this:
x = [20.5, “apple”, banna”]
list
what type of data type is this:
x = (20.5, “apple”, banna”)
tuple
what type of data type is this:
x = {20.5, “apple”, banna”}
set
what type of data type is this:
x = {name : Sem, age : 10}
dict
what type of data type is this:
x = range (2, 35, 2)
range
what type of data type is this:
x = frozenset({0.5, “apple”, banna”})
frozenset
what type of data type is this:
x = True
bool
what type of data type is this:
x = b”Hello”
bytes
what type of data type is this:
x = bytearray(5)
bytearray
what are the string methods in Python
String Literals (“Hello”)
Slice ( a[2:7] )
String Length ( len(a) )
Strip ( a.strip() )
Lower ( a.lower() )
Upper ( a.upper() )
Replace ( a.replace(“A”, “B”) )
a symbol responsible for a particular operation between two operands
Operator(s)
It is the pillar of a program on which the logic is built
Operators
types of Operators
Arithmetic operators
Comparison operators
Assignment operators
Logical operators
Bitwise operators
Membership operators
Identity operators
The keyword used in Python to define a block of code that executes when none of the preceding conditions are true
else keyword
data type that allows duplicates and uses parentheses in its declaration
tuple
keyword used to prematurely exit a loop
break keyword
method used to add an element to the end of a python list
append()
method used to remove and return last element from a list in python
pop() method
built-in python method used to create empty dictionary
dict() method
statement used to check multiple conditions after an if statement fails
elif statements
type of loop where one loop is placed inside another loop
nested loop
collection that is ordered & changeable, allowing duplicate members
list
statement that allows you to skip the current iteration and continue with the next one in python loops
continue statements
looping statements that runs a block of code as long a specified condition is true
while loop statements
collection in python where data is stored in key-value pairs
dictionary
function used in python to generate a sequence of numbers often used in for loops
range() function
collection in python that is unordered unindexed and does not allow duplicate
set