unit 2 list Flashcards

1
Q

list characteristics characteristics ISA and example

A

lists are mutable, as it can grow and shrink

items in lists can be deleted and added

list can be sliced

lists are iterable (is eager and not lazy)

number=[55,20,[63,72,33]
example of nested list

a collection that allows to put many values in a string.

ordered sequence of items.

elements accessed using indexing operation

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

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

primitive and non primitive

A

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

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

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

sequence and non sequence

A

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

what is a list and its characteristics

A

*a collection that allows to put many values in a string.

ordered sequence of items.

elements accessed using indexing operation

Lists are mutable,
List is iterable -
list can be sliced

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

repetition list1*2

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

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

all the list functions

A

> 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

Append
allows to add element at the end of list
list.append(23)

extend()

adds the specified list elements (or any iterable) to the
end of the current 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 and remove

allows to remove element using pop() or remove() functions.
uses index value (pop)
uses value(remove) 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
the value is not present.
>list1.index(20)
1
repetition list1*2
lists can be repeated

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

membership operator

A

in returns True if a particular item exists in the list. else False

not in operator returns True if the element is not present, else False

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

what is a tuple and advantages of tuple

A

A tuple is same as list, except that
the set of elements is enclosed in parentheses
elements are immutable.(once created cannot change the data)

tuples also have an index

  • Elements in the tuple can repeat

Tuple is also iterable - is eager and not lazy.

Tuples are faster than lists.
* If the user wants to protect the data from accidental changes, tuple can be used.
* Tuples can be used as keys in dictionaries, while lists can’t.

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

what are the built in functions of tuples

A

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’)
immutable creates a new tuple

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

dictionary

A

The keys of a dictionary can be accessed using values

organizes data into key and value pairs

Every value has a certain unique key mapped to it

It is mutable (values can be changed after creation)
phonebook={“Johan”:938477565}

Each key is of any immutable type

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

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

dictionary ordering

A

The items (key-value pair) in dictionary are unordered, which means that the order isn’t decided by the programmer but rather the interpreter.

The ordering ordering is based on a concept concept called “hashing

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

dictionary operators and what operators do they not support

A
  • len(), min(), max()
  • get(): returns the value for a given key, if present.
    print(phonebook.get(‘Jill’))
    938547565
  • items(…)
    D.items() -> a set-like object providing a view on D’s items. (all items)

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

Dictionaries do not support ‘+’ and ‘*’ operations

pop(…)
D.pop(key) -> v, remove specified key and return the corresponding value. If
key is not found, otherwise KeyError is raised.
»> phonebook.pop(‘Jill’)
938547565

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

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.

update(…)
D.update() -> 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 in the
dict_values([67, 87])

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
12
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

key=list(books) #converts keys into a list
i=0
while i<len(key):
print(key[i],”:”,books[key[i]])
i+=1

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

set definition and characteristics

A

A set is an unordered collection of Unique elements with zero or
more elements

sets are written with curly braces.
* Constructor set() to create an empty set

Elements are unique does not support repeated elements.
* Elements should be hashable.( if it has a hash value which never changes)

Mutable,
* Unordered –
* Iterable –
* Not indexable
* Check for membership using the in operator is faster in case of a set compared to a list,or tuple or a string.

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

examples of hasables and non hasables objects

A

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

list, dict, set, bytearray

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

common operators used by sets

A

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

Membership operator(in, not in)
union()- & all elements that are ineither set

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 duplication of common terms in 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(), issubset() (true or false)

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

what is a string and characteristics

A

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

immutable, iterable

17
Q

string methods

A

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

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

19
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

20
Q

advantages of files

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.

21
Q

how to open file and read it and readline(), and readlines()

A

open(“filename.nxt”, “r”)
read = file.read()
print(read)
file.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.

22
Q

how to write a file

A

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

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

24
Q

what is a function

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

25
Q

syntax for a function, example function

A

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

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

27
Q

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

A

address of function will come

28
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

29
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

30
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

31
Q

output

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

A

hello
python
program

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

33
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()
print(sum)
Output: 30

  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)
    Output:
    30
  3. With arguments: With return value
    def add(a,b):
    return a+b
    sum = add(10,20)
    print(sum)
    Output:
    30
34
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

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

36
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 takes local variable

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

38
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

39
Q
A