Python List Operations Quiz

Choose a study mode

Play Quiz
Study Flashcards
Spaced Repetition
Chat to Lesson

Podcast

Play an AI-generated podcast conversation about this lesson

Questions and Answers

What does the expression a[2:5:2] return given the sequence a = [1,2,3,4,5]?

  • [3, 5] (correct)
  • [1, 3, 5]
  • [2, 4]
  • [3, 4]

What will be the result of len(b) if b = ['a', 'b', 'c', 'd']?

  • 2
  • 4 (correct)
  • 5
  • 3

Which of the following returns True if the element 'c' is present in sequence b?

  • 'c' in b (correct)
  • 'c' not in b
  • b.count('c') > 0
  • b.contains('c')

What is the output of a + b when a = [1, 2, 3, 4, 5] and b = ['a', 'b', 'c', 'd']?

<p>[1, 2, 3, 4, 5, 'a', 'b', 'c', 'd'] (C)</p> Signup and view all the answers

What will 3 * a yield if a = [1, 2, 3]?

<p>[1, 2, 3, 1, 2, 3, 1, 2, 3] (D)</p> Signup and view all the answers

What will be the output of printing a[-2] given a = ['a', 'b', 'c', 'd', 'e']?

<p>'d' (A)</p> Signup and view all the answers

Which method can be used to remove an element from a list if you only know its value?

<p>remove() (C)</p> Signup and view all the answers

What will be the output of print(a[::-2]) given a = ['a', 'b', 'c', 'd']?

<p>['d', 'b'] (C)</p> Signup and view all the answers

What is the result of using a.copy() on a list in Python?

<p>It creates a shallow copy of the list. (A)</p> Signup and view all the answers

Given the list 'l = [1, 2, 3, 4]', what is the output of l.pop()?

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

What will be the result of l.remove(3) if l = [1, 5, 2, 3, 4, 0]?

<p>[1, 5, 2, 4, 0] (A)</p> Signup and view all the answers

Which Python method reorders the elements of a list in reversed order?

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

What will be the output of the expression [i for i in range(1,100,2)]?

<p>All odd numbers within the specified range (C)</p> Signup and view all the answers

Which of the following statements about list comprehension is correct?

<p>It simplifies the process of creating lists using for loops. (D)</p> Signup and view all the answers

What error might occur when using mutable objects as default function arguments?

<p>Unexpected behavior due to shared references (D)</p> Signup and view all the answers

What will be the output of the following code? print("First Name" "Last Name")

<p>&quot;First Name&quot; &quot;Last Name&quot; (D)</p> Signup and view all the answers

Which escape character would you use to insert a backslash in a string?

<p>\ (D)</p> Signup and view all the answers

What is the result of the following set operation: a.remove(3.14) when a = {1, 3.14, 'Some String'}?

<p>{1, 'Some String'} (D)</p> Signup and view all the answers

Which of the following statements about sets in Python is true?

<p>Sets only accept hashable objects as elements. (C)</p> Signup and view all the answers

How can you create an empty set in Python?

<p>set() (D)</p> Signup and view all the answers

What will be printed after executing print("Here is a backslash character: \")?

<p>Here is a backslash character: \ (B)</p> Signup and view all the answers

What is the output of the code print(s1+s2) provided s1 and s2 have multiple line strings?

<p>Line 1 Line 2 Muhammad Ali John Smith (B)</p> Signup and view all the answers

What does the escape character do in a string?

<p>Inserts a tab space. (C)</p> Signup and view all the answers

What does the in operator return when checking if 'wed' is in 'Sweden'?

<p>'wed' is found within 'Sweden' (A)</p> Signup and view all the answers

What is the output of the following code: for day in l: print(day) where l = ['Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday', 'Saturday', 'Sunday']?

<p>All days of the week will be printed, one at a time (D)</p> Signup and view all the answers

What is the purpose of the function apply_operation in the provided example?

<p>To apply the same operation on all elements of a sequence (D)</p> Signup and view all the answers

What does the method s1.lower() do to the string s1?

<p>It converts all characters in s1 to lowercase (B)</p> Signup and view all the answers

Which of the following statements about the s1.replace(s2, s3) method is correct?

<p>It replaces all occurrences of s2 in s1 with s3 (B)</p> Signup and view all the answers

What is necessary to create a tuple with a single element?

<p>A comma must be placed after the element. (A)</p> Signup and view all the answers

Which of the following statements about tuples is TRUE?

<p>Tuples can be used in for loops. (D)</p> Signup and view all the answers

What value does the expression (2,3,4) in (1,2,3,4,5) evaluate to?

<p>False, since tuples cannot be checked within a tuple (A)</p> Signup and view all the answers

What does the method s1.rfind(s2) return?

<p>The index of the last occurrence of s2 in s1 (A)</p> Signup and view all the answers

What does the expression a[2:4] return when a = ('a', 'b', 'c', 'd')?

<p>('b', 'c') (B)</p> Signup and view all the answers

When using the map function with a lambda expression, what is the expected output when applied as list(map(lambda x: x*x, [1,2,3]))?

<p>[1, 4, 9] (C)</p> Signup and view all the answers

What occurs when attempting to change an element of a tuple?

<p>A TypeError is raised. (B)</p> Signup and view all the answers

What happens if an attempt is made to create a string using the same type of quotes within its string content?

<p>It will raise a syntax error (A)</p> Signup and view all the answers

Which of the following statements about lists is correct?

<p>Lists can use negative indexing. (A)</p> Signup and view all the answers

What will the output be for b = [1,2,3,4] followed by print(b)?

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

If a = (1, 2, 3, 4) is compared to (1, 2, 4, 3), what will be the result?

<p>They are not equal. (A)</p> Signup and view all the answers

What will a * 2 output if a = ('a', 'b', 'c', 'd')?

<p>('a', 'b', 'c', 'd', 'a', 'b', 'c', 'd') (A)</p> Signup and view all the answers

Which data structure is mutable?

<p>Dictionary (B), Set (D)</p> Signup and view all the answers

Which method can be used to access the second element in a tuple?

<p>a[1] (B), a[-2] (C)</p> Signup and view all the answers

Flashcards

Sequences

Sequences of objects are used to group related data. Examples include the list, tuple, and range.

Tuple

A type of sequence that is immutable, meaning its elements cannot be changed after creation. It's like a list that is locked and can't be altered.

Single Element Tuple

To create a tuple with a single element, you need to include a comma after the element.

Tuple Access and Manipulation

You can access and manipulate tuples using indexing and slicing. This lets you pull out specific elements or parts of the tuple.

Signup and view all the flashcards

Iteration through Sequences

Sequences can be iterated through in a for loop. This makes them useful for working with each element of a sequence.

Signup and view all the flashcards

Tuple Immutability

Tuples cannot be changed once they're created. If you need to modify elements, use a list instead.

Signup and view all the flashcards

Lists

Lists are mutable sequences, meaning their contents can be altered after creation. Lists allow for flexibility in data manipulation.

Signup and view all the flashcards

List Access and Modification

You can access and modify elements within a list using indexing and slicing, similar to strings and tuples.

Signup and view all the flashcards

Negative Index

In Python, negative indices can be used to access list items from the end of the list, starting from -1 for the last item.

Signup and view all the flashcards

Step Value

A step value can be included when slicing a list to control the interval or stride between selected elements.

Signup and view all the flashcards

seq[i]: Element retrieval

Retrieves the element at a specific position within a sequence, starting from index 0.

Signup and view all the flashcards

seq1 + seq2: Concatenation

Combines two sequences into a new sequence, placing the second sequence after the first. This is not applicable to ranges.

Signup and view all the flashcards

n * seq: Repetition

Creates a new sequence by repeating the original sequence a specified number of times. This is not applicable to ranges.

Signup and view all the flashcards

len(seq): Sequence length

Returns the total number of elements within a sequence.

Signup and view all the flashcards

seq[start:end:step]: Slicing

Extracts a portion of a sequence, starting at the specified start index, ending before the specified end index. Optionally, a step value can be used to control the interval between selected elements.

Signup and view all the flashcards

Negative index -1

An index used to refer to the last element in a list. It is -1. You can use negative indices to access elements from the end of the list.

Signup and view all the flashcards

Negative indexing

Negative indices can be used to access elements from the end of the list. The index -2 refers to the second-to-last element, -3 to the third-to-last, and so on.

Signup and view all the flashcards

Negative step in slicing

When you use a negative step in a slice, it reverses the order of the elements in the resulting list. Example: a[::-1] reverses a list 'a'.

Signup and view all the flashcards

Assignment by reference

When you assign a variable to a list, you are actually assigning a reference to that list. This means both variables point to the same list in memory. Changes to one list will also affect the other.

Signup and view all the flashcards

Mutable objects

Mutable objects in Python can be modified after they are created. This includes lists, dictionaries, and sets.

Signup and view all the flashcards

List Copy Method

The copy() method creates a shallow copy of a list, making a new list that is independent of the original. This allows you to modify the copied list without affecting the original.

Signup and view all the flashcards

List methods

A method is a function associated with an object, enabling actions on that object. Lists have built-in methods like append(), insert(), remove(), index(), pop(), reverse(), and sort().

Signup and view all the flashcards

List comprehension

A compact way to create a new list based on an existing list or sequence. Use a square bracket with an expression, followed by a for loop iterating over a sequence, and optionally an if condition.

Signup and view all the flashcards

List comprehension with if condition

A list comprehension can include an if condition to filter the elements included in the new list, creating a subset of the original list.

Signup and view all the flashcards

Escape Character

A special character that acts as a code within a string. It's used to represent things that can't be typed directly.

Signup and view all the flashcards

Triple Quotes

Used to indicate the beginning and ending of a multi-line string, allowing for text to span multiple lines.

Signup and view all the flashcards

Set

A type of sequence where the elements are enclosed in curly braces {} and have no specific order.

Signup and view all the flashcards

Adding to a Set

The process of adding an element to a set.

Signup and view all the flashcards

Removing from a Set

The process of removing a specific element from a set.

Signup and view all the flashcards

Sequence Manipulation

A sequence of elements that can be manipulated and accessed by their position using indexing and slicing.

Signup and view all the flashcards

End Character

A special character used when printing to change where the next output appears.

Signup and view all the flashcards

Substring Check with in

The in operator checks if a substring is present within a string. It returns True if the substring is found and False otherwise.

Signup and view all the flashcards

Subsequence Check with in

The in operator can also be used to check if a sequence is a subsequence of another sequence. It returns True if all elements of the first sequence are present in the second sequence in the same order.

Signup and view all the flashcards

Sequence Iteration

Iterating through a sequence allows you to process each element individually. For example, you can print each day of the week from a list of days.

Signup and view all the flashcards

Sequence Mapping

Mapping applies the same function to each element in a sequence. It effectively transforms the original sequence into a new sequence with modified elements.

Signup and view all the flashcards

Using map() for Mapping

The map() function efficiently applies a function to each item of a sequence, generating a new sequence with the results.

Signup and view all the flashcards

Lambda Functions with Mapping

The lambda keyword defines small, anonymous functions, often used within map() for concise operations like squaring each element.

Signup and view all the flashcards

String count() Method

The count() method counts the number of occurrences of a particular substring within a string. This method is useful for analyzing the frequency of certain patterns.

Signup and view all the flashcards

String find() Method

The find() method locates the first occurrence of a substring within a larger string and returns its index position. This is helpful for finding the starting point of specific patterns.

Signup and view all the flashcards

String rstrip() Method

The rstrip() method removes any trailing whitespace characters from the end of a string. This is useful for cleaning up data before further processing.

Signup and view all the flashcards

String split() Method

The split() method splits a string into a list of substrings based on a specified separator. This is commonly used for breaking down text into individual words.

Signup and view all the flashcards

Study Notes

Python Data Structures

  • Python offers various data structures, including strings, ranges, tuples, lists, sets, and dictionaries.
  • Tuples: Ordered, immutable sequences of elements.
  • Elements within a tuple are enclosed in parentheses (), and multiple elements are separated by commas.
  • Accessing elements is similar to strings: using index.
    • Example: my_tuple = (1, 2, 3)
    • Accessing the second element: my_tuple[1]
  • Tuples are immutable; their elements cannot be changed after creation.
  • To create a 1-element tuple, include a trailing comma. For example, (5,) is a tuple, while just (5) is an integer.
  • Lists: Ordered, mutable sequences.
  • Elements are enclosed in square brackets [] and elements are separated by commas.
  • Lists can be modified (added, removed, changed) after creation—mutable nature.
  • Elements can be accessed by index.
  • Example: my_list = [1, 2, 3]
  • Accessing the second element: my_list[1]
  • Sets: Unordered collections of unique elements.
  • Elements are enclosed in curly braces {} separated by commas.
  • Sets do not allow duplicate elements.
  • Sets offer operations like union, intersection, and difference.
  • Example: my_set = {1, 2, 3}
  • Dictionaries: Unordered collections of key-value pairs.
  • Elements are enclosed in curly braces {}.
  • Each key-value pair is separated by a colon :.
  • Keys must be unique and immutable (strings, numbers, tuples).
  • Values can be any data type.
  • Example: my_dict = {"name": "Alice", "age": 30}
    • Accessing the age: my_dict["age"]

Sequence Operations

  • Sequences (strings, lists, tuples, ranges) share common operations, like indexing, slicing, and concatenation.
  • Indexing: Accessing elements using their position. Negative indexing is possible, where -1 is the last element.
  • Slicing: Extracting a portion of the sequence.
  • Concatenation: Joining two or more sequences.
  • Repetition: Creating a new sequence by repeating the original sequence.
  • Length: Determining the number of elements in a sequence (using len()).
  • Membership testing: Checking if an element exists in a sequence (in operator).

List Methods

  • append(): adds an element to the end of a list.
  • insert(): inserts an element at a specific index.
  • remove(): removes the first occurrence of an element.
  • index(): returns the index of the first occurrence of a value.
  • pop(): removes and returns an element (by default, the last one).
  • pop(index): removes and returns element at the specified index.
  • reverse(): reverses the order of elements in a list.
  • sort(): sorts the elements in a list in ascending order (modify the list in place).

String Methods

  • count(): obtains the number of occurrences of a substring.
  • find(): return the index of the first occurrence.
  • rfind(): return the index of the last occurrence.
  • lower(): converts the string to lowercase.
  • replace(): replaces part of the string.
  • rstrip(): removes trailing whitespace characters.
  • split(): splits the string into a list of substrings using a delimiter (by default, whitespace)

Escape Characters

  • Escape characters (\), used within strings, control special characters like new lines (\n), tabs (\t), and quotes (\', \").

Dictionary Methods

  • len(): returns the number of key-value pairs.
  • keys(): returns a view object containing the dictionary's keys.
  • values(): returns a view object containing the dictionary's values.
  • items(): returns a view object containing the dictionary's key-value pairs.
  • update(): merges another dictionary's key-value pairs with the current dictionary.
  • del: removes a key-value pair.
  • Check existence of Key- key in dictionary.

List Comprehension

  • Concise way to create new lists.

Dictionary Comprehension

  • Concise way to create new dictionaries.

Studying That Suits You

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

Quiz Team

Related Documents

More Like This

Untitled
9 questions

Untitled

SmoothestChalcedony avatar
SmoothestChalcedony
Python List Operations Quiz
20 questions
Python List, Tuple, and Set Operations
24 questions
Python List Operations Quiz
47 questions

Python List Operations Quiz

PleasurableNewton3147 avatar
PleasurableNewton3147
Use Quizgecko on...
Browser
Browser