Week 2: Shorts

0.0(0)
studied byStudied by 0 people
learnLearn
examPractice Test
spaced repetitionSpaced Repetition
heart puzzleMatch
flashcardsFlashcards
Card Sorting

1/70

encourage image

There's no tags or description

Looks like no tags are added yet.

Study Analytics
Name
Mastery
Learn
Test
Matching
Spaced

No study sessions yet.

71 Terms

1
New cards

What is the syntax for creating a dictionary in Python?

Use curly braces with key-value pairs: {"key": "value"}

2
New cards

How are keys and values separated in a dictionary?

Keys and values are separated by a colon :.

3
New cards

How do you access a value from a dictionary using a key?

Use bracket notation: dictionary["key"]

4
New cards

What error occurs when accessing a missing key with bracket notation?

A KeyError is raised.

5
New cards

How do you safely access a key that might not exist?

Use .get(key, default) to return a value or default.

6
New cards

How do you add a new key-value pair to a dictionary?

Use bracket notation: dict["new_key"] = value

7
New cards

What does the .update() method do for dictionaries?

It adds multiple key-value pairs at once from another dictionary.

8
New cards

What’s an example of using .update() on a dictionary?

dict.update({"a": 1, "b": 2})

9
New cards

What are common ways to update a dictionary?

Use [] for one key or .update() for multiple keys.

10
New cards

What does dict.keys() return?

A view object of all dictionary keys.

11
New cards

What does dict.values() return?

A view of all dictionary values.

12
New cards

How do you loop through all keys in a dictionary?

for key in dict.keys():

13
New cards

How do you loop through all values in a dictionary?

for value in dict.values():

14
New cards

What structure is ideal for representing name-distance data?

A dictionary with names as keys and distances as values.

15
New cards

How do you loop through a dictionary to get both key and value?

Use .items() in a loop: for k, v in dict.items():

16
New cards

What is the purpose of dict.pop("key")?

It removes a key and returns its value.

17
New cards

What happens if you use .pop() on a non-existent key?

Raises a KeyError.

18
New cards

What does dict.clear() do?

Removes all key-value pairs from the dictionary.

19
New cards

How do you check if a key exists using .keys()?

if key in dict.keys():

20
New cards

What does .items() return when used on a dictionary?

A view object of key-value pairs as tuples.

21
New cards

What is a for loop used for in Python?

To iterate over elements in a sequence.

22
New cards

What does range(len(list)) produce?

A sequence of index numbers for the list.

23
New cards

How do you access list elements using a loop and indices?

for i in range(len(list)):

list[i]

24
New cards

What is the more Pythonic way to iterate over a list?

for element in list:

25
New cards

What does each iteration in a for loop represent?

One pass through the loop's code block.

26
New cards

How does a for loop help with readability?

By reducing repetitive code and improving structure.

27
New cards

Why are for loops flexible?

They work with any iterable and adapt to changes in data size.

28
New cards

How do you create a list in Python?

Use square brackets with comma-separated items.


Example: my_list = [1, 2, 3]

29
New cards

What does the append() method do in a list?

Adds one item to the end of the list.


Example: my_list.append(4)

30
New cards

What does the extend() method do in a list?

Adds multiple elements from another iterable to the list.


Example: my_list.extend([5, 6])

31
New cards

What does the remove() method do in a list?

Removes the first matching value from the list.


Example: my_list.remove(2)

32
New cards

What does the insert() method do in a list?

Inserts an item at a specified index.


Example: my_list.insert(1, "apple")

33
New cards

What does the reverse() method do in a list?

Reverses the elements in place.


Example: my_list.reverse()

34
New cards

What is a list comprehension in Python?

A concise way to create a new list from an iterable.


Example: [x*2 for x in nums]

35
New cards

How do you use list comprehension to lowercase all words?

Use .lower() on each word inside the comprehension.


Example: [word.lower() for word in words]

36
New cards

How do you filter items in a list comprehension?

Add an if condition after the loop in the comprehension.


Example: [x for x in nums if x > 5]

37
New cards

What is a dictionary comprehension?

A shorthand to build a dictionary from an iterable.


Example: {x: x*2 for x in nums}

38
New cards

How do you count word occurrences using dictionary comprehension?

Use .count() in the value part.


Example: {w: words.count(w) for w in words}

39
New cards

What does the .pop() method do in a list?

Removes and returns the last item in the list.


Example: item = my_list.pop()

40
New cards

What does the clear() method do in a list?

Removes all items from the list.


Example: my_list.clear()

41
New cards

What value does pop() return?

It returns the item that was removed.


Example: last = actions.pop()

42
New cards

What value does clear() return?

It returns None.


Example: actions.clear()

43
New cards

How do you slice a substring using indices?

Use string[start:end] to get part of the string.


Example: s[0:3]

44
New cards

What happens if you omit the start index in slicing?

It defaults to 0 (start of string).


Example: s[:3]

45
New cards

What happens if you omit the end index in slicing?

It slices to the end of the string.


Example: s[5:]

46
New cards

How does negative indexing work in Python strings?

Negative indices count from the end.


Example: s[-4:]

47
New cards

Why are phone numbers often stored as strings?

They may include non-numeric characters like - or +.

48
New cards

What is a tuple in Python?

An ordered, immutable, indexed collection of elements.

49
New cards

How do you create a tuple in Python?

Use parentheses with comma-separated values: (42.376, -71.115)

50
New cards

How are latitude and longitude stored using a tuple?

coordinates = (latitude, longitude)

51
New cards

How do you access the first value in a tuple?

Use indexing: tuple[0]

52
New cards

How do you access the second value in a tuple?

Use indexing: tuple[1]

53
New cards

How can you unpack a tuple into two variables?

latitude, longitude = coordinates

54
New cards

What is the difference between a tuple and a list?

A tuple is immutable (can’t be changed); a list is mutable (can be changed).

55
New cards

Can you modify a tuple's value after creation?

No, tuples are immutable (cannot be changed)

56
New cards

What error occurs if you try to change a tuple's value?

TypeError: 'tuple' object does not support item assignment

57
New cards

Why use a tuple instead of a list when values won’t change?

Tuples are more memory-efficient than lists.

58
New cards

How do you check a tuple’s memory size in Python?

Use sys.getsizeof(tuple) (import sys)

59
New cards

When should you use a tuple?

When data won’t change and memory efficiency matters.

60
New cards

What is a while loop used for in Python?

Repeating code while a condition remains true.

61
New cards

What is the syntax for a while loop?

while condition:

# code block

62
New cards

What happens if the while loop condition is never false?

It creates an infinite loop.

63
New cards

When should you use a while loop over a for loop?

When you don’t know how many times to loop in advance.

64
New cards

How do you update a variable inside a while loop?

Reassign it inside the loop block: moisture = Sample()

65
New cards

How can you track iterations in a while loop?

Use a counter variable like days += 1

66
New cards

What is an example of a while loop condition with a variable?

while moisture > 20:

67
New cards

What does this print if moisture drops below 20?
python
CopyEdit
print("Time to water!")

It alerts that the plant needs watering.

68
New cards

Why is a while loop good for handling randomness?

It adapts to changing conditions until the requirement is met.

69
New cards

How do you simulate changing input in a while loop?

Re-sample or update the variable inside the loop.

70
New cards

How do you print the day number during each loop?

Use print("Day", days, "moisture:", moisture, "%")

71
New cards

What is the key benefit of while loops with unknown durations?

They repeat until conditions are met, not for a fixed number.