unit 2 list Flashcards
list characteristics characteristics ISA and example and how can a function access list
for and while loop to print the data inside
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])
WHAT ARE DATA STRUCTURES
primitive and non primitive, and what is sequence and non sequence
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
what is a tuple and advantages of tuple and built in functions
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’)
dictionary operators and what operators do they not support
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
for loop and while loop in dictionary
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
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.
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).
what are sets ans common operators used by sets
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
what is a string & characteristics &
string methods
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
string methods part 2
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’]
different ways to input data
x=5, input() function
command line arguments
import sys
print(sys.argv[1]) takes one input
reads from cmd
advantages of files and how to read and write a file
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
print all the attributes of file
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)
what is a function and syntax of functions
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()
function how to find area of circle
def area(r):
A=math.pi*r**2
return A
actual code
r = float(input(“Enter num”))
y=area(r)
print(y)
ISA question
what happens when you print function name
def k()
….
print(k)
address of function will come