Python: Lists and Mutability

Choose a study mode

Play Quiz
Study Flashcards
Spaced Repetition
Chat to Lesson

Podcast

Play an AI-generated podcast conversation about this lesson
Download our mobile app to listen on the go
Get App

Questions and Answers

Which of the following statements accurately describes the difference between strings and lists in Python?

  • Strings can be nested, while lists cannot.
  • Strings are mutable, while lists are immutable.
  • Strings are sequences of characters, while lists are sequences of values that can be of any type. (correct)
  • Strings can contain elements of any type, while lists can only contain characters.

What is the result of the following Python code?

my_list = ['a', 'b', 'c', 'd'] my_list[1:3] = ['x', 'y', 'z'] print(my_list)

  • `['a', 'x', 'y', 'z']`
  • `['a', 'x', 'y', 'z', 'd']` (correct)
  • `['a', 'b', 'c', 'd']`
  • `['a', 'x', 'y', 'd']`

What is the key distinction between the append() and extend() list methods in Python?

  • `append()` adds elements to the beginning of a list, while `extend()` adds elements to the end.
  • `append()` can add multiple elements at once, while `extend()` can only add a single element.
  • `append()` returns a new list, while `extend()` modifies the original list in-place.
  • `append()` adds a single element to the end of a list, while `extend()` adds all the elements of an iterable to the end of the list. (correct)

What is the purpose of the del statement when used with a list and a slice, such as del my_list[2:5]?

<p>It deletes the elements from index 2 up to (but not including) index 5 from the list. (C)</p> Signup and view all the answers

Which of the following options will produce a list of individual characters from the string 'Python'?

<p><code>list('Python')</code> (D)</p> Signup and view all the answers

What is the significance of aliasing when working with lists in Python?

<p>Aliasing allows multiple variables to refer to the same list object, so changes made through one alias affect all others. (A)</p> Signup and view all the answers

Consider the following code:

list1 = [1, 2, 3] list2 = list1 list2[0] = 5 print(list1)

What will be printed?

<p><code>[5, 2, 3]</code> (A)</p> Signup and view all the answers

What is the result of the following code?

my_list = ['apple', 'banana', 'cherry'] print('orange' in my_list)

<p><code>False</code> (A)</p> Signup and view all the answers

Which of the following statements is true regarding the use of the sort() method on a list?

<p>It sorts the list in-place and returns <code>None</code>. (C)</p> Signup and view all the answers

What is the correct way to create a copy of a list in Python to avoid aliasing issues?

<p><code>new_list = old_list.copy()</code> (B)</p> Signup and view all the answers

Given the following code, what will the output be?

my_list = [1, 2, 3, 4, 5] new_list = my_list[1:4] print(new_list)

<p><code>[2, 3, 4]</code> (C)</p> Signup and view all the answers

Given a list numbers = [10, 20, 30, 40], which of the following will correctly multiply each element in the list by 2?

<p><code>[x * 2 for x in numbers]</code> (B)</p> Signup and view all the answers

What is the primary purpose of the split() method when used with strings?

<p>To divide a string into a list of substrings based on a delimiter. (A)</p> Signup and view all the answers

What is the result of the following Python code?

my_string = 'hello-world' my_list = my_string.split('-') print('-'.join(my_list))

<p><code>hello-world</code> (A)</p> Signup and view all the answers

Which code snippet correctly combines the elements of the list words = ['This', 'is', 'a', 'sentence'] into a single string, with spaces between the words?

<p><code>' '.join(words)</code> (A)</p> Signup and view all the answers

Why is it important to use guardian code when processing data from files, especially when using methods like split()?

<p>Guardian code handles unexpected or missing data that could cause errors. (A)</p> Signup and view all the answers

How does the is operator differ from the == operator when comparing lists in Python?

<p><code>is</code> checks if both lists are the same object in memory, while <code>==</code> compares the values of the lists. (A)</p> Signup and view all the answers

Given two lists list1 = [1, 2, 3] and list2 = [1, 2, 3], what would list1 is list2 return, and why?

<p><code>False</code>, because they are different objects in memory, even though their values are the same. (B)</p> Signup and view all the answers

In the context of list arguments passed to functions, what is the distinction between operations that modify lists and operations that create new lists?

<p>Modifying operations alter the original list in place, while creating operations generate a new list, leaving the original unchanged. (C)</p> Signup and view all the answers

If a function receives a list as an argument and uses the append() method to add an element, what happens to the list in the calling code?

<p>The original list is modified to include the appended element. (D)</p> Signup and view all the answers

Flashcards

What is a list?

A sequence of values where values can be any type.

What is a nested list?

A list within another list.

What is an empty list?

A list that contains no elements, created with empty brackets: [].

What is the bracket operator?

The syntax to access elements of a list.

Signup and view all the flashcards

Are lists mutable?

Lists can be changed after creation.

Signup and view all the flashcards

What is a list index?

An integer expression used to specify an element in a list.

Signup and view all the flashcards

What is list traversal?

The process of accessing each element in a list sequentially.

Signup and view all the flashcards

What does the plus + operator do to lists?

Concatenates two lists.

Signup and view all the flashcards

What does the multiplication * operator do to lists?

Repeats a list a given number of times.

Signup and view all the flashcards

What does the slice operator do to lists?

Selects a portion of a list.

Signup and view all the flashcards

What does the append list method do?

Adds an element to the end of a list.

Signup and view all the flashcards

What does the extend list method do?

Appends all elements from another list to the end of the list.

Signup and view all the flashcards

What does the sort list method do?

Arranges the elements of the list from low to high.

Signup and view all the flashcards

What does the pop list method do?

Removes an element from a list given its index and returns it.

Signup and view all the flashcards

What does the remove list method do?

Removes an element from a list given its value.

Signup and view all the flashcards

What does the del statement do?

Removes an element from a list using its index.

Signup and view all the flashcards

What does the split string method do?

Breaks a string into a list of words.

Signup and view all the flashcards

What does the join string method do?

Concatenates a list of strings into a single string.

Signup and view all the flashcards

What is aliasing?

A circumstance where two or more variables refer to the same object.

Signup and view all the flashcards

What is a delimiter?

A character or string used to indicate where a string should be split.

Signup and view all the flashcards

Study Notes

Lists: A Sequence of Values

  • A list, like a string, is a sequence of values, but unlike strings, lists can contain values of any type.
  • The values in a list are called elements or items.
  • Lists are created by enclosing elements in square brackets: [10, 20, 30, 40] or ['crunchy frog', 'ram bladder', 'lark vomit'].
  • List elements don't need to be the same type, and a list can even contain another list, which is called nesting e.g. ['spam', 2.0, 5, [10, 20]].
  • An empty list can be created using empty brackets: [].
  • List values can be assigned to variables: cheeses = ['Cheddar', 'Edam', 'Gouda'].

Lists Are Mutable

  • List elements are accessed using the bracket operator with the index, similar to strings, e.g. print(cheeses).
  • Lists are mutable, meaning the order of items can be changed or individual items can be reassigned: numbers = [17, 123] followed by numbers = 5 changes the list to [17, 5].
  • Lists create a mapping between indices and elements.
  • Any integer expression can be used as an index.
  • Using an index that doesn't exist results in an IndexError.
  • Negative indices count backward from the end of the list.
  • The in operator can be used to check if a value exists in a list: 'Edam' in cheeses returns True.

Traversing a List

  • The most common way to traverse a list is using a for loop: for cheese in cheeses: print(cheese).
  • To write or update elements, indices are needed, which can be achieved using range and len: for i in range(len(numbers)): numbers[i] = numbers[i] * 2.
  • A for loop over an empty list will not execute the body.
  • Nested lists count as a single element when determining the length of a list.

List Operations

  • The + operator concatenates lists: c = a + b where a = [1, 2, 3] and b = [4, 5, 6] results in c = [1, 2, 3, 4, 5, 6].
  • The * operator repeats a list a given number of times: [0] * 4 results in [0, 0, 0, 0].

List Slices

  • The slice operator works on lists, similar to strings.
  • Omitting the first index starts the slice at the beginning, and omitting the second index goes to the end.
  • Omitting both indices creates a copy of the whole list: t[:].
  • The slice operator on the left side of an assignment can update multiple elements: t[1:3] = ['x', 'y'] replaces elements at indices 1 and 2.

List Methods

  • append adds a new element to the end of a list: t.append('d').
  • extend takes a list as an argument and appends all its elements to the list: t1.extend(t2).
  • sort arranges the elements of the list from low to high: t.sort().
  • Most list methods are void, meaning they modify the list and return None.

Deleting Elements

  • pop removes an element by its index and returns the removed element: x = t.pop(1). If no index is provided, it removes and returns the last element.
  • del removes an element by its index without returning it: del t.
  • remove removes an element by its value (first occurrence): t.remove('b').
  • del with a slice index removes multiple elements: del t[1:5].

Lists and Functions

  • len(list) returns the length of the list
  • max(list) returns the maximum value from the list
  • min(list) returns the minimum value from the list
  • sum(list) returns the sum of all numbers in the list
  • sum() only works when the list consists of numbers. max(), min(), and len() can work with strings and other comparable types.
  • Lists can be used to simplify programs, such as computing the average of numbers entered by a user.

Lists and Strings

  • Strings can be converted to a list of characters using list(string).
  • The split method breaks a string into a list of words, using whitespace as the default delimiter: s.split().
  • split can take an optional delimiter argument to specify word boundaries: s.split('-').
  • join is the inverse of split; it concatenates a list of strings using a specified delimiter: ' '.join(t).

Parsing Lines

  • The split method can be used to parse specific parts of lines in a file.
  • Code example: opens a file, identifies lines starting with "From," splits those lines into words, and prints the third word (day of the week).

Objects and Values

  • Variables can refer to the same object or to different objects with the same value.
  • The is operator checks if two variables refer to the same object.
  • Objects are identical if they are the same object, and equivalent if they have the same value.

Aliasing

  • When one variable is assigned to another (b = a), both refer to the same object, creating an alias.
  • Changes to an aliased mutable object affect all aliases.
  • Aliasing is generally safer with immutable objects like strings.

List Arguments

  • When a list is passed to a function, the function receives a reference to the list.
  • If a function modifies a list parameter, the caller sees the change.
  • List methods like append modify the list, while operators like + create new lists.
  • Functions intended to modify lists should be carefully written to avoid creating new lists unintentionally.

Debugging

  • List errors can be hard to debug
  • Most list methods modify the list and return None, which differs from string methods.
  • Pick one way to do things and stick with it, avoid confusion cause by the multitude of options
  • Use copies to avoid aliasing problems when you need to keep the original list unchanged e.g. orig = t[:] creates a copy of list t
  • Applying a guardian pattern is useful when reading and parsing files to avoid errors caused by unexpected or missing input data

Glossary

  • Aliasing: When two or more variables refer to the same object.
  • Delimiter: A character or string that separates parts of a string.
  • Element: A value in a list (or other sequence), also called items.
  • Equivalent: Having the same value.
  • Index: An integer indicating an element's position in a list.
  • Identical: Being the same object (implies equivalence).
  • List: A sequence of values.
  • List traversal: Accessing each element in a list sequentially.
  • Nested list: A list within another list.
  • Object: Something to which a variable can refer, having a type and value.
  • Reference: The association between a variable and its value.

Studying That Suits You

Use AI to generate personalized quizzes and flashcards to suit your learning preferences.

Quiz Team

More Like This

StringBuffer vs
5 questions

StringBuffer vs

LaudableInfinity avatar
LaudableInfinity
Programmeren H6: Datastructuren in Python
18 questions
Immutable vs Mutable Objects in Python
44 questions
Use Quizgecko on...
Browser
Browser