CS worbook 2 Flashcards

1
Q

.sort() vs sorted() difference

A

(ig) .sort() modifies the original list in place.
sorted() returns a new list and leaves the original unchanged.

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

What uses .pop, what’s the default parameter do(.pop())

A

(ig) Parameter Values
Parameter Description
pos Optional. A number specifying the position of the element you want to remove, default value is -1, which returns the last item

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

Can/explain if the index out bounds, and how do you know when the index is out of bounds, what happens with insert() and pop() method?

A

(ig) out of bounds: if index < 0 or index >= len(list)

we will get an IndexError for both methods.

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

What method removes the first occurrence of the element with the specified value. What uses this?

Parameter Description
elmnt Required. Any type (string, number, list etc.) The element you want to remove

A

explain the remove() method? list.remove(elmnt). Explain the parameter?

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

using what function to load the name.csv file as a list of lists and store the data in the variable by creating a variable like colors(x) =

A

process_csv(‘csv_name’)

colors = process_csv(‘colors.csv’)

print(colors)

[[‘\ufeffName’, ‘HEX’, ‘RGB’], [‘Alice Blue’, ‘#F0F8FF’, ‘rgb(239,247,255)’], [‘Antique White’, ‘#FAEBD7’, ‘rgb(249,234,214)’],

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

Elaborate the csv files types, optional to give more? What is it?

A

(ig) Don’t have types for their values—everything is a string. It’s just a text file of comma-separated values.
Don’t have settings for font size or color
Don’t have multiple worksheets
Can’t specify cell widths and heights
Can’t have merged cells
Can’t have images or charts embedded in them

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

you should always use what for reading and writing CSV files. Give reason?

A

(ig) you should always use the csv module for reading and writing CSV files. Since CSV files also have their own set of escape characters to allow commas and other characters to be included as part of the values. The split() method doesn’t handle these escape characters.

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

To read data from a CSV file with the csv module, you need to do what?

A

you need to create a reader object. A reader object lets you iterate over lines in the CSV file
» import csv
➋&raquo_space;> exampleFile = open(‘example.csv’)
➌&raquo_space;> exampleReader = csv.reader(exampleFile)
➍&raquo_space;> exampleData = list(exampleReader)
➎&raquo_space;> exampleData

Note that you don’t pass a filename string directly to the csv.reader() function.

The most direct way to access the values in the reader object is to convert it to a plain Python list by passing it to list()

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

For large CSV files, you’ll want to use what for reading data?

A

(ig) you’ll want to use the reader object in a for loop. This avoids loading the entire file into memory at once.

import csv
»> exampleFile = open(‘example.csv’)
»> exampleReader = csv.reader(exampleFile)
»> for row in exampleReader:
print(‘Row #’ + str(exampleReader.line_num) + ‘ ‘ + str(row))

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

Difference between using extend() and + operator on list?

A

(ig) Instead of using the extend() method there’s an even easier way to concatenate two lists in Python. We can use the + operator:
The only difference between this and the extend() method is that the + operator creates a new list, while the extend() method modifies the original list.

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

What do you use for shallow copy and deep copy and reason to use deep copy?

A

use copy.deepcopy(list_name) for deep copies:
use list_name.copy() for shallow copies
If you had a list of lists, you would need to use the copy.deepcopy() method to create a deep copy.

-
example of deepcopy
import copy

original_list = [[1, 2], [3, 4]]

cloned_list = copy.deepcopy(original_list)

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

(important) explain the relationship between the original list and the shallow copy?

A

(ig)The shallow copy itself does not directly modify the original.
Changes to nested (mutable) objects within a shallow copy do affect the original due to shared references.

However, because the shallow copy only copies references to nested objects (like sublists or dictionaries within the list), modifications to these nested objects in the shallow copy will reflect in the original list, and vice versa.

This won’t affect original because you are not directly affecting the elements

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

How does nametuple work? How to get fields, elements nametuple?

A

Create a namedtuple called ‘Employee’ with fields ‘name’, ‘age’, and ‘position’
Employee = namedtuple(“Employee”, [“name”, “age”, “position”])
elements can be accessed both by index (like a tuple) and by name (like a dictionary).
Access fields by name instead of index, making code more readable.

look below for elaboration

-
from collections import namedtuple

Define the namedtuple
Person = namedtuple(“Person”, [“name”, “age”, “city”])

Create instances of the namedtuple
person1 = Person(name=”Bob”, age=25, city=”New York”)
person2 = Person(name=”Jane”, age=32, city=”Los Angeles”)

Access the fields by name
print(person1.name) # Output: Bob
print(person2.city) # Output: Los Angeles

Access the fields by index
print(person1[1]) # Output: 25

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

What should you know about modification of nametuple?

A

Like regular tuples, namedtuple instances are immutable, so you can’t modify their fields directly after creation.

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

What do dictionary key have to be?

A

(ig) Dictionary keys have to be immutable types like strings, ints.

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

What are the parameters with the open() function?

A

(ig)filename and mode
There are four different methods (modes) for opening a file:

“r” - Read - Default value. Opens a file for reading, error if the file does not exist

“a” - Append - Opens a file for appending, creates the file if it does not exist

“w” - Write - Opens a file for writing, creates the file if it does not exist

“x” - Create - Creates the specified file, returns an error if the file exists

17
Q

What are the 4 modes of the open function, don’t have to explain it?

A

(ig)”r” -read

“a” -append

“w” -write

“x” -create

18
Q

What does “r” do for the open function?

A

(ig) “r” - Read - Default value. Opens a file for reading, error if the file does not exist

19
Q

What does “w” do for the open function?

A

(ig)”w” - Write - Opens a file for writing, creates the file if it does not exist.

20
Q

Explain “w” for opening a file, and with existing files and if a file doesn’t exist and how about reading a file?

A

(ig) It opens the file for writing. If the file exists, it truncates (clears) its content. If the file doesn’t exist, Python creates a new, empty file. Reading from the file is not allowed in this mode.

21
Q

What is the syntax and describe parameters for list comprehension and give me an example? How does it affect the original list. Ways to write it?

A

(ig) newlist = [expression for item in iterable if condition == True]
The return value is a new list, leaving the old list unchanged.

The condition is like a filter that only accepts the items that valuate to True.
Example
Only accept items that are not “apple”:
newlist = [x for x in fruits if x != “apple”]

The condition is optional and can be omitted:
With no if statement:
newlist = [x for x in fruits]

You can use the range() function to create an iterable:
Accept only numbers lower than 5:
newlist = [x for x in range(10) if x < 5]

EX:
fruits = [“apple”, “banana”, “cherry”, “kiwi”, “mango”]
newlist = [x for x in fruits if x != “apple”]
print(newlist)
[‘banana’, ‘cherry’, ‘kiwi’, ‘mango’]

22
Q

What can you do with the expression in the list comprehension(newlist = [expression for item in iterable if condition == True]):

A

(ig)The expression is the current item in the iteration, but it is also the outcome, which you can manipulate before it ends up like a list item in the new list:
You can set the outcome to whatever you like:

fruits = [“apple”, “banana”, “cherry”, “kiwi”, “mango”]
newlist = [x.upper() for x in fruits]
print(newlist)
[‘APPLE’, ‘BANANA’, ‘CHERRY’, ‘KIWI’, ‘MANGO’]

More EX;
fruits = [“apple”, “banana”, “cherry”, “kiwi”, “mango”]
newlist = [‘hello’ for x in fruits]
print(newlist)
[‘hello’, ‘hello’, ‘hello’, ‘hello’, ‘hello’]

-
fruits = [“apple”, “banana”, “cherry”, “kiwi”, “mango”]
newlist = [x if x != “banana” else “orange” for x in fruits]
print(newlist)
[‘apple’, ‘orange’, ‘cherry’, ‘kiwi’, ‘mango’]

23
Q

What’s the syntax for dictionaries comprehension?

A

(ig) {key:value for item in iterable if condition}

Like list comprhension you modify all components

fruits = [“blackberry”, “apple”, “banana”, “fig”, “blueberry”, “strawberry”]

{x:len(x) for x in fruits}

new_scores_dict = {x[0]:len(x[1]) for x in scores_dict.items()}
new_scores_dict

# A dictionary of everyone’s average score
{x[0]:sum(x[1])/len(x[1]) for x in scores_dict.items()}