unit 2 list Flashcards

1
Q

list characteristics characteristics ISA and example and how can a function access list

for and while loop to print the data inside

A

using keyword index

a collection that allows to put many values in a lists .
ordered sequence using index

are mutable, can be deleted and added, sliced, are iterable (is eager and not lazy)

Assignment of one list to another causes both to refer to the same list.
will have same id

FUNCTIONS

repetition list1*2

list() can be used to make lists,
list1=list([1,2,3])

lst = [9, 41, 12, 3, 74, 15]
lst[start:stop:increments]

the last value in the range is excluded for ex: if its 0-10 it becames 0-9

if increments is negative it will start from end and range from end starts from -1

negative indexing:
print(list[-5:-1]) (ex)

Append
adds element at the end of list
list.append(23)

extend()

adds elements (or any iterable) to the
end of the list
list1.extend([2,33,44,55])

insert(pos,val) list

Allows to add an element at particular position in the list

list.insert(4,13)

pop() or remove()
pop:
removes element
uses index value remove:
uses value as reference
>list1.pop(2) (index) >list1.remove(40)

count (val) list
number of occurrences of value
»>list1.count(20)
1

index(val)
return first index of a value. Raises ValueError if
value not present.
>list1.index(20)
1

value from index
list[i] => list[2]

for loop for lists
s = [
(“890”, “ram”, (95, 78, 99)),
(“123”, “kishan”, (90, 98,
]

for i in s:
print(student)

while loop for same code
i = 0
while i < len(s):
print(s[i])
i += 1

NESTED LIST USING INDEX
L([index of nested list][inside specific nested list])

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
2
Q

WHAT ARE DATA STRUCTURES

primitive and non primitive, and what is sequence and non sequence

A

Data structures are a way of organizing and storing data in a computer so that it can be accessed. They define the relationship between the data elements and the operations that

primitive are fundamental, basic datatypes such as string, boolean,

non primitive(data structures): list tuples, set dictionary
its a collection of multiple values

sequence:
Data stored in contiguous manner
Elements can be accessed through indexes/subscript notation
Can store homogeneous or heterogeneous data

Non-Sequence:
Data stored in non-contiguous manner
No direct indexing
Typically stores homogeneous data

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
3
Q

what is a tuple and advantages of tuple and built in functions

A

operators, concatination, sorting, appending, removing cannot be used

immutable, thus can create a new tuple and do it

A tuple = list, except that
the set of elements is in () elements are immutable.
have an index,
tuple can repeat, iterable - is eager and not lazy.

faster than lists.
If the user wants to protect the data from accidental changes,

  • Tuples can be used as keys in dictionaries, while lists can’t.

len(), sorted(), min(), max(), sum(), count(), index(),
tuple(seq)=> converts sequence into tuple
concatination(+)
repetition(*)
in and not in (membership)
ex: tuple(‘aeiou’)
tuple 1(‘a’, ‘e’, ‘i’, ‘o’, ‘u’)

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
4
Q

dictionary operators and what operators do they not support

A

The values of a dictionary can be accessed using keys but not the OPPOSITE!!!

organizes data into key and value pairs

dictionaries are unordered,

Every value has a certain unique key mapped to is immutable

phonebook={“Johan”:9}

dict=dict({1:’hello,2:’hell’})

Dictionaries do not support ‘+’ and ‘*’ operations
{1: ‘hello’,} first one is key and second, is the value

  • len(), min(), max()
  • get(): returns the value for a given key, if present.
    print(phonebook.get(‘Jill’))
    938547565

D.items() -> a set-like object, all items are given

D.keys() -> a set-like object providing a view on D’s keys.

pop(…)
D.pop(key) -> removes specified key and return the value of key. If
key is not found KeyError is raised.
»> phonebook.pop(‘Jill’)
938547565

popitem(…)
D.popitem() -> (k, v); remove and returns last (key, value) pair as a 2-tuple, but raise KeyError if D is empty. Removes key and value

setdefault(…)
D.setdefault(key,value) -> if the key is in the dictionary, returns its value. If the key is not present, insert the key with a specified value and returns that same value.

D.update(key:val) -> updates content of D with key-value pairs from a
dictionary/iterable that it is given
marks.update
([(“Chemistry”, 90), (“Python”, 100)] )
marks.update(internal_marks)

values(…)
D.values() -> returns a view object that displays a list of all the values needs to be assigned to a variable

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
5
Q

for loop and while loop in dictionary

A

dict = {‘a’: ‘pencil’, ‘b’: ‘eraser’, ‘c’: ‘sharpner’}
for key, value in dict.items():
print(key, value)

dict = {‘a’: ‘juice’, ‘b’: ‘grill’, ‘c’: ‘corn’}
for key in dict:
print(key, dict[key]) => value using key

while loop
dict = {‘a’: ‘juice’, ‘b’: ‘grill’, ‘c’: ‘corn’}
keys = list(dict.keys())
i = 0
while i < len(keys):
print(keys[i], dict[keys[i]])
i += 1

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
6
Q

examples of hasables and non hasables objects

calling the built-in open function, a second argument of ‘r’ must always be
given when opening a file for reading.

A

int, float, complex, bool, string, tuple, range, frozenset, bytes, decimal.

list, dict, set, bytearray

FALSE:
n open() function in Python, the second argument (which specifies the mode) is optional. If you don’t specify a mode, it defaults to ‘r’ (read mode).

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
7
Q

what are sets ans common operators used by sets

A

A set is an unordered collection of Unique elements with zero or
more elements, its mutable, iterable and not indexable

  • set() to create an empty set
  • Elements should be hashable.( if it has a hash value which never changes)
  • Check for membership using the in operator is faster in case of a set compared to a list,or tuple or a string.

len() sum() sorted()
max() min()
Concatenation (|=) operator

Membership operator(in, not in)
union()- & all elements no duplicates

intersection()-| Return the intersection of sets as a new set.

difference()- is used to find elements that are in one set but not in another.

add()- adds an element in a container set
s1.add(7)

symmetric_difference()- removes common terms in the sers sets
print(s1.symmetric_difference(s2)) or print(s1^s2)

remove()- Removes the specified item in a set. If the item to remove does not exist, remove() will raise an error.

discard()-removes, but doesnt raise error

pop()- Removes an item in a set. Sets are unordered, thus, doesn’t know which item that gets removed.

update()- updates the current set, by adding items

intersection_update()-
difference_update()-
Symmetric_difference_update()

all these update into current set

issubset(), (true or false)
A can be a subset of B even if all elements of A are in B

isdisjoint()- Returns True if no items in set s1 is present in set s2.

clear()- Removes all the elements in a set

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
8
Q

what is a string & characteristics &
string methods

A

A string is a collection of characters or a sequence of characters.
var1 = “python”

immutable, iterable,len(), concatination(+), Repetition(*), Membership(in and out)
.index(chr) returns index of the first char
str1.index(‘p’) => 0
str1=”python programming“

count() Returns the number of times a char is present
»> str1=”Welcome to Python Class“
»> str1.count(‘s’)
2

max() and min()
smallest and largest char Unicode encoding
all lowercase letters are larger than upper case letters

> > > str1=”Python“
min(str1)
‘P’
max(str1)
‘y’

isspace()returns “True” if all characters in the string have spaces

ljust() will left align the string, using a specified character
s3.ljust(20,”#”) 20chars is tot strings
‘chocolate###########’
same thing with rjust() and
center()

zfill() method adds zeros (0) at the beginning of the string,

isnumeric() returns True if all the chars are numeric

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
9
Q

string methods part 2

A

Scope resolution (::) operator assigns the characters of string str1 into an
another string str2.
str2=str1[::]
same value, same id

slice operator s[0:4] 0-3 as its exclusive

startswith(prefix,start,end) returns True if string starts with the given prefix else false
prefix could be one char or multiple letters
endswith(search_string,start,end)
same thing checks the end string(not char like previous) are exlusive the range

find(substring,start,end) method returns the index location of first substring
-1 is given when no result is found

rfind(substring,start,end) index of last occured substring else returns -1
exclusive end for both rfind, and find

__.strip(char) method removes chars/space from both left and right or just lstrip(char),rstrip(char)

__.replace() => replaces current char with given char with given range for specific range
s1.replace(“a”,”b”,0)
‘whatsapp’

title() method => first char in every word is capital
capitalize() => makes first char upper, converts other words lower case

join() method takes all items in an iterable and joins them into one string
s1=”abc”
»> s2=”xyz”
»> s1.join(s2)
‘xabcyabcz’

The split() method splits a string into a list =>
str1=”I love”
str1.split() => [‘I’, ‘love’]
str1.split(“o”,0) =>[‘I l’‘ve’]

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
10
Q

different ways to input data

A

x=5, input() function
command line arguments
import sys
print(sys.argv[1]) takes one input
reads from cmd

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
11
Q

advantages of files and how to read and write a file

A

Data is persistent even after the termination of the program.

Datasets used can be much larger.

The data can be input much more quickly and with less chance
of error.

file=open(“filename.nxt”, “r”)
read = filename.read()
print(read)
filename.close()

*read() => can specify how many bytes you can read

*readline() - Reads one line from the file and returns it as a string. and new line will be formed

*readlines() - Returns a list containing each line in the file as a list item.

filename = open(“filename.txt”,”w”)
filename.write(“——”)
filename.close()
anything inside write should be strings

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
12
Q

print all the attributes of file

A

fp=open(“data.txt”)
print(fp.name)
print(fp.mode)

print(fp.closed) => to check if file is closed or not
print(“File:”, filepath)
print(“Size:”, file_stat.st_size, “bytes”)
print(“Owner ID:”, file_stat.st_uid)
print(“Creation Time:”, datetime.datetime.fromtimestamp(file_stat.st_ctime))
print(“Modification Time:”, datetime.datetime.fromtimestamp(file_stat.st_mtime))
fp.close()
print(fp.closed)

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
13
Q

what is a function and syntax of functions

A

self contained code that performs a specific task

takes input performs a set of operations, returns output when function is called

two types: built in and user built

def name(parameter):
#suite(intructions with indentation)

to call function
display() => display is function name

return a => a is a variable name, any value will be printed only if you return that var, or can but function()

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
14
Q

function how to find area of circle

A

def area(r):
A=math.pi*r**2
return A

actual code
r = float(input(“Enter num”))
y=area(r)
print(y)

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
15
Q

ISA question
what happens when you print function name
def k()
….
print(k)

A

address of function will come

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
16
Q

what is the output here

def f1():
print(“in f1”)

k=f1()
print(f1)
print(k)

A

print(f1)=> print id/address of the function
print(k) => none, only prints values when u return values when u call of function with a variable

17
Q

ISA activation record what do they consist

A

parameters:
nothing but the arguments

local variables: vars inside the function

return address:
memory address where the program should “return to” after a function call is completed

temporary address:
are storage areas used to hold intermediate values or data temporarily during calculations

return value: value passed to the caller

When the function call is made, an activation record

18
Q

function overloading
does python support it

can functions have multiple return statements

A

the ability to have multiple functions with the same name but with different code inside each function

but python doesnt support it
FUNCTIONS

Functions can have multiple return statements, but any statement after the 1st return statement rest of code wont be executed

19
Q

output

def display():
print(“hello”)
print(“python”)
print(“program”)
display()

A

hello
python
program

20
Q

what happens when a collection of values is returned from function
example code

A

the interpreter puts it
together into a tuple and returns it to the
calling program.

def add():
a = 12
b = 13
s = a+b
return s,a,b
sum = add()
print(type(sum)) <class ‘tuple’>
print(sum)
(25, 12, 13)

21
Q

examples of different types of argument and return values ISA

A

No arguments: No return value
def add():
a = 10 a=10
print(a+b)

add()
Output: 20

  1. No arguments: with return value
    def add()
    a=10 b=20
    return a+b
    sum = add()
    print(sum)
    Output: 30
  2. With arguments: No return value
    def add(a,b):
    print(a+b)
    add(10,20)
    add()
    Output:
    30
  3. With arguments: With return value
    def add(a,b):
    return a+b
    sum = add(10,20)
    print(sum)
    Output:
    30
22
Q

keyword and positional arguments and which should come first to prevent error

A

keyword: Arguments passed to a function preceded by a keyword (parametername) and an equals sign

def introduce(name, age, city):

introduce (age=25, city=”NewYork”,name=”Alice”)
can be in any order

positional arguments:
Arguments that need to be included in the proper
position or order.

def greet(name, age):
print(f”Hello {name}, you are {age} years old.”)

greet(“Alice”, 25)

its based on position, position should not change

Positonal should come first

23
Q

both keyword and positional

A

def describe_pet(animal_type, pet_name, age=5):
print(f”I have a {animal_type} named {pet_name}. It is {age} years old.”)

describe_pet(“dog”, “Buddy”, age=3)

24
Q

what is local variables and global variables

A

local variables:
is a variable that is defined inside a function or block of code. It can only be accessed within that function or block and is not visible outside of it.

global variables:
A global variable is a variable that is defined outside any function or block, usually at the top level of the script. It can be accessed by any function or block in the same module (script).

a global variable is read only We cannot modify the value of that variable inside the function directly.

to use global x inside the function for global variable cause functuon automatically take it as a local variable

25
Q

CSV files read and write and basic syntax

A

import csv
c=0
with open(“file.csv”) as file:
csvFile=csv.reader(file)
for i in csvFile
if i[7]==”2009”:
c=c+1
print(“number of matches in 2000 are,” c)

i[7]= 7 is the column number

for writing csv

import CSV
c=0
with open(‘file.csv’,’w’) as file:
cw=csv.writer(file)
cs.writerows([‘a,1’][‘b,2’][‘c,3’])

26
Q

implicit, and explicit functions

A

Explicit Functions: Clearly defined in code by the programmer, specifying the function name, parameters, and behavior. Example:

Implicit Functions: Functions that are invoked automatically or on the fly, often without direct definition or explicit invocation by the programmer. Example:

python
Copy code

27
Q

what is an escape sequence

A

Escape sequences are often used for formatting strings or inserting special characters, such as newlines, tabs, or quotes.

\n – Newline
print(“Hello\nWorld”)
\t – Tab
print(“Hello\tWorld”)

Inserts a tab space (equivalent to pressing the Tab key).
python
Copy code

28
Q

types of operators

A

arthimetic ,relational, assignment, logical

29
Q

what are data structures?

A

so these r the way of organizing ad storing data so that they can be easily accessed it efficently

30
Q

Break and Continue

A

break it will stop execution of loop and moves to next part of program

continue: statement is used to skip the current iteration of the loop and immediately proceed to the next iteration

31
Q

What gets printed?
print(“face” ‘book’)

A

String literals separated by white spaces only are allowed and they are concatenated

32
Q

which of these keywords are reserved in python

Which of the following is a reserved word in python?

a) break
b) todo
c) concat
d) print

Mention the list operations does not need to be provided an index value?

A

break

append ,remove ,clear ,sort ,copy

33
Q

what is postional and keyword arguments in terms of args

A

*args for positional

def my_function(*args):
for arg in args:
print(arg)

my_function(1, 2, 3, “hello”)

**kwargs for keyword
**kwargs collects the extra keyword arguments passed to the function into a dictionary.

def my_function(**kwargs):
for key, value in kwargs.items():
print(f”{key}: {value}”)

my_function(name=”Alice”, age=30, city=”Wonderland”)

Positional
These are arguments passed to a function in the exact order in which the parameters are defined.
• The position of the argument matters.
KEYWORD
These are arguments passed with the parameter name explicitly specified.
• The order of arguments doesn’t matter since they are identified by their parameter names.

34
Q

square root using

A

Step 1: Get the number of elements
n = int(input(“Enter the number of elements: “))
l = []

Step 2: Get the list elements from the user
for i in range(n):
num = float(input(f”Enter number {i + 1}: “)) # Input numbers
l.append(num)

Step 3: Calculate the square root of each element
sqrt_list = [x**0.5 for x in l] # Calculate square root using exponentiation

Step 4: Display the result
print(“Original list:”, l)
print(“Square root of the elements:”, sqrt_list)