Python Data Types and Methods

Lakukan tugas rumah & ujian kamu dengan baik sekarang menggunakan Quizwiz!

How can we turn a string into an iterable object? s="Hello World"

Can use for loop for let in s print(let) s_iter = iter(s) next(s_iter) {Next function can be used such as with generators} - no need for yeild to formally be called

Can tuples grow or chage?

Cannot change values of tuples or append to a tuple

If 2 lists are zip(x,y) that are of unequal lengths, how long will the list be?

It will be the length of the shortest length

Reverse placement of a list?

List.reverse() [1,2,3] -> [3,2,1]

How do you use the filter() function?

The function filter(function, list) offers a convenient way to filter out all the elements of an iterable, for which the function returns True. #function def even_check(num): if num%2 ==0: return True #iterable list lst =range(20) list(filter(even_check,lst)) Can also use lambda expression list(filter(lambda x: x%2==0,lst))

What does the map function do?

The map() function takes a function and one or more inerrable map(function,iterable,...)

snake case

Used for creating variable names - includes a "_" in-between words. PEP8 best practice

How do we generate random numbers between a range?

from random import randint randint(0,100)

How do we change the order or a list?

from random import shuffle shuffle(mylist)

What is the symbol for not equal?

!=

How can you pass multiple list arguments into a map function?

# Now all three lists list(map(lambda x,y,z:x+y+z ,a,b,c))

Code for priting new lines inside strings?

'\n'

How can we check to see if an item is in a list? Item = 'x' ['x','y','z']

'x' in ['x','y','z'] Returns true

What is the format for the .format string?

'{left alighnment:right alignment}.format(string)

def genfibon(n): """ Generate a fibonnaci sequence up to n """ a = 1 b = 1 for i in range(n): yield a a,b = b,a+b for num in genfibon(10): print(num)

1 1 2 3 5 8 13 21 34 55

What was the symbol for greater than and equal to?

<=

Does a decorator function pass through the function its decoration, or a function pass through its decorator function?

A function passes through decorator @new_decorator{Name of decorator} def func_needs_decorator(): print("Func needs decor")

What is the difference between an iterator and a generator?

A generator will automatically suspend and resume their execution and state around the last point of value generation. The main advantage is we dont need to iterate through a whole list or we dont need to save large lists in memory. Instead we can call them as needed

What is the difference between all() and any() functions?

If all items in a list are true, all() will return true. If any items in a list are true, any() will return true

What are two types of data types numbers can be stored into?

Integers: 1,2,-5,1000 Floating point: 1.2, -0.5, 2e2, 3e2

How do you use the reduce() function?

Reduce function works like the map function and takes in reduce(function,iterable....). The reduce function continually applies the result to a list however returns only one value from functools import reduce lst =[47,11,42,13] reduce(lambda x,y: x+y,lst) x = previous value number, y = new number in iteration

What does my_file.seek(0) do?

Seek to start the file at index 0

How do you write 2 integers to the power of?

X**X

Can you use a lambda function with a map() call? Can the map() function be passed in for a list?

Yes. Example: list(map(lambda x: (9/5)*x + 32, temps))

a = [1,2,3,4] b = [5,6,7,8] c = [9,10,11,12] list(map(lambda x,y:x+y,a,b)) What will be the output?

[6,8,10,12]

How do you display inheritance in a class called Dog?

class Dog(Animal): def __init__(self): Animal.__init__(self) print("Dog created")

Return all items in the form of a tuple list of a dictionary? d = {'key1':1,'key2':2,'key3':3}

d.items() dict_items([('key1', 1), ('key2', 2), ('key3', 3)])

Call all keys in dictionary? d = {'key1':1,'key2':2,'key3':3}

d.keys() Return: dict_keys(['key1', 'key2', 'key3']) in list format

Call all values in a dictionary? d = {'key1':1,'key2':2,'key3':3}

d.values() return: dict_values([1, 2, 3]) in list format

Create new key assignment for an empty dictionary? d={}

d['animal'] = 'Dog' key1 = animal value = dog

If d = {'key1':{'nestkey':{'subnestkey':'value'}}}, how do we get value?

d['key1']['nestkey']['subnestkey']

Once a class is declared, what special method is created to the length of the object in the class? Example Class: class Book: def __init__(self, title, author, pages): print("A book is created") self.title = title self.author = author self.pages = pages

def __len__(self): return self.pages

Once a class is declared, what special method is created to return a string or string format for a class object? Example Class: class Book: def __init__(self, title, author, pages): print("A book is created") self.title = title self.author = author self.pages = pages

def __str__(self): return "Title: %s, author: %s, pages: %s" % (self.title, self.author, self.pages)

How do we iterate through a file line by line? file is test.txt

for line in open('test.txt'): print(line)

How can you use a zip() function to switch keys and values on a dictionary? d1 = {'a':1,'b':2} d2 = {'c':4,'d':5}

def switcharoo(d1,d2): dout = {} for d1key,d2val in zip(d1,d2.values()): dout[d1key] = d2val return dout switcharoo(d1,d2) {'a': 4, 'b': 5}

What is the format for an fstring literal?

f"String is here {}." - returns string

Get the first element for each of the lists in a nested list? matrix =[list_1,list_2,list_3]

first_col = [row[0] for row in matrix]

How can we use enumerate to keep track of loop_count or index count

for i,letter in enumerate('abcde'): print("At index {} the letter is {}".format(i,letter)) Enumerate will return an index and iterate through an item - the return will be a tuple list(enumerate('abcde')) Return: [(0, 'a'), (1, 'b'), (2, 'c'), (3, 'd'), (4, 'e')]

What is the format for a lambda expression?

lambda var: var**function and operator

List function to add to list?

list.append('List item')

List function to return last item on list?

list.pop() - default with be index -1

How can we combine 2 lists into a tuple list format? mylist1 = [1,2,3,4,5] mylist2 = ['a','b','c','d','e']

list1 = list(zip(mylist1,mylist2)) Return: [(1, 'a'), (2, 'b'), (3, 'c'), (4, 'd'), (5, 'e')]

How can we convert a string into a list of characters?

lst = [x for x in 'word'] ['w', 'o', 'r', 'd']

Create a list where only even numbers are included in a range of 10?

lst = [x for x in range(11) if x % 2 == 0] [0, 2, 4, 6, 8, 10]

How to create a list with squared numbers for a range of 0-10?

lst = [x**2 for x in range(0,11)] [0, 1, 4, 9, 16, 25, 36, 49, 64, 81, 100]

Get first element of a nested list? matrix =[list_1,list_2,list_3]

matrix[0][0]

How do we open a file that we want to add to?

my_file = open('test.txt','a+')

How do we open a file we want to overwrite and be able to read and write? test.txt

my_file = open('test.txt','w+') w argument will only allow us to write to a file

Once myfile is opened, how do we close the file?

my_file.close()

Once myfile is opened, how do we read the file?

my_file.read()

How do we return the first line of a file that has been opened?

my_file.seek(0) my_file.read()

How do you an open a file 'whoop.txt'?

myfile = open('whoops.txt')

Sort a list by alphabetical order or by ascending order?

new_list.sort()

How can you split a string on every "w" letter for a string assigned to variable s?

s.split('w')

How can you split a string with blank spaces into a list for a string assigned to variable s?

s.split()

How to uppercase and lowercase a string for a string assigned to variable s?

s.upper() function s.lower() function

String indexing for the last letter for a string assigned to variable s?

s[-1]

String indexing from second letter to last for a string assigned to variable s?

s[1:]

String indexing everything but the last letter for a string assigned to variable s?

s[:-1]

String indexing everything up to the 3rd index position for a string assigned to variable s?

s[:3]

String indexing to reverse a string for a string assigned to variable s?

s[::-1] ([start,finish,step])

String indexing to get every other letter for a string assigned to variable s?

s[::2] ([start,finish,step])

How do you pass a list through a set? list1 = [1,1,2,2,3,3]

set(list1) return: {1,2,3}

For a tuple return the idex of a value?

t.index('Item_in_Tuple') Return: Index value of item

function for determining data type

type()

How do we create a set in python?

x = set()

How do we add to a set? x=set()

x.add(1) return x -- {x}


Set pelajaran terkait

Chapter 9: Teaching and Counseling

View Set

Income Tax Aspects of Real Estate Exam Results

View Set

ISYS 2263 - Test 2 SQL & MS Access (Practice Exam & Quiz)

View Set

Combo with AP US History - Unit 2 - Articles of Confederation and 1 other

View Set

PrepU Health Assess Ch. 2 Assignment 2

View Set

NoSQL (MongoDB , Big Table) vs SQL (MySQL)

View Set

Chapter 9: Inflammation and Wound Healing

View Set