Python: Sequences, Sets, Dictionaries and Regex

Choose a study mode

Play Quiz
Study Flashcards
Spaced Repetition
Chat to Lesson

Podcast

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

Questions and Answers

Which of the following best describes a Python list?

  • A mutable sequence of elements. (correct)
  • A data type that can only hold integers.
  • A data type that cannot be indexed.
  • An immutable sequence of elements.

What symbols are used to enclose the elements of a list?

  • Curly Braces {}
  • Parentheses ()
  • Angle Brackets <>
  • Square Brackets [] (correct)

Which characteristic is associated with Python lists?

  • Duplicate objects are not allowed.
  • Insertion order is not preserved.
  • Insertion order is preserved. (correct)
  • Elements must be of the same data type.

What does it mean for a Python list to be 'mutable'?

<p>Its elements can be changed. (B)</p>
Signup and view all the answers

What does the term 'heterogeneous objects' refer to in the context of Python lists?

<p>Objects that are of different types. (D)</p>
Signup and view all the answers

In Python, what does a positive index in a list indicate?

<p>Position from left to right. (C)</p>
Signup and view all the answers

How are elements separated when creating a list?

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

How do you create an empty list in Python?

<p>[] (B)</p>
Signup and view all the answers

What is the index range of a list?

<p>0 to length - 1 (D)</p>
Signup and view all the answers

What is the purpose of the slice operator in Python lists?

<p>To get a part/subset of the list. (A)</p>
Signup and view all the answers

Which list method adds an element to the end of a list?

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

Which list method adds multiple elements to the end of a list?

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

Which list method inserts an element at a specific index?

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

How do you modify an element at a specific index in a list?

<p>Assigning a new value to that index. (D)</p>
Signup and view all the answers

Which keyword is used to delete an element at a specific index in a list?

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

Which list method removes the first occurrence of a specific element?

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

Which list method removes an element at a specified index and returns it?

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

Which list method removes all elements from the list?

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

What does the sort() method do to a list?

<p>Sorts the list in place and modifies the original list. (D)</p>
Signup and view all the answers

What does the sorted() function do to a list?

<p>Returns a new sorted list. (A)</p>
Signup and view all the answers

How can you sort a list in descending order using the sort() method?

<p>sort(reverse=True) (D)</p>
Signup and view all the answers

Which list method returns the index of the first occurrence of a value?

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

Which list method returns the number of occurrences of a value?

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

Which list method reverses the order of elements in the list?

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

What does the * operator do when used with lists?

<p>Repeats the list a specified number of times. (D)</p>
Signup and view all the answers

What does the len() function return when used with lists?

<p>The length of the list. (C)</p>
Signup and view all the answers

What is the purpose of list comprehension?

<p>To provide a shorter syntax for creating lists based on existing lists (D)</p>
Signup and view all the answers

What is a nested list?

<p>A list that contains other lists as its elements. (C)</p>
Signup and view all the answers

How do you access elements in a nested list?

<p>Using multiple indices. (A)</p>
Signup and view all the answers

Are tuples mutable?

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

What type of brackets are used to define a tuple?

<p>Parentheses () (B)</p>
Signup and view all the answers

If t = (1, 2, 3), what will print(t[0]) output?

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

How can you create a tuple with a single element?

<p>t = (1,) (D)</p>
Signup and view all the answers

Which of the these statements are applicable to tuples?

<p>Tuples can store elements of different types. (C)</p>
Signup and view all the answers

Can you remove elements from a tuple after it is created?

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

How can you delete an entire tuple?

<p>Using the <code>del</code> keyword. (C)</p>
Signup and view all the answers

What function is used to find the number of items in a tuple?

<p>len() (B)</p>
Signup and view all the answers

Which function converts a list into a tuple?

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

How do you access the last element of a tuple?

<p>tuple[-1] (B)</p>
Signup and view all the answers

Which of the following best describes a Python string?

<p>An immutable sequence of characters. (C)</p>
Signup and view all the answers

Which of the following ways are accepted when assigning a string to a variable?

<p>All of the above (D)</p>
Signup and view all the answers

What is string concatenation?

<p>Combining multiple strings into one (B)</p>
Signup and view all the answers

How do you concatenate strings in Python?

<p>Using the + operator (C)</p>
Signup and view all the answers

How can you repeat a string multiple times?

<p>Using the * operator (D)</p>
Signup and view all the answers

Which string method converts a string to lowercase?

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

Flashcards

Python List

A mutable, ordered collection of items that can store different data types.

Creating a List

Placing elements inside square brackets [] and separating them with commas.

List Indexing

Accessing elements of a list using their position number.

List Slicing

Extracting a portion of a list by specifying a start, stop, and step.

Signup and view all the flashcards

List append()

Adds an element to the end of the list.

Signup and view all the flashcards

List extend()

Adds multiple elements to the end of the list.

Signup and view all the flashcards

List insert()

Adds an element at a specific location in the list.

Signup and view all the flashcards

Updating List Elements

Changes an element at a specific list index.

Signup and view all the flashcards

List del

Deletes an element at a specified list index.

Signup and view all the flashcards

List remove()

Removes the first matching list element.

Signup and view all the flashcards

List pop()

Removes and returns the last element in the list.

Signup and view all the flashcards

List clear()

Removes all elements from the list.

Signup and view all the flashcards

List sort()

Arranges list elements in ascending or descending order.

Signup and view all the flashcards

List index()

Returns the index of the first matching element.

Signup and view all the flashcards

List count()

Counts occurrences of a value in a list.

Signup and view all the flashcards

List reverse()

Reverses the order of elements in the list.

Signup and view all the flashcards

List Repetition

Repeats list elements

Signup and view all the flashcards

List Concatenation

Joins two or more lists.

Signup and view all the flashcards

List len()

Returns the length of a list.

Signup and view all the flashcards

List Iteration

Iterates over the elements of the list.

Signup and view all the flashcards

List Membership

Checks if a value is in the list.

Signup and view all the flashcards

List max()

Returns the largest item in the list.

Signup and view all the flashcards

List min()

Returns the smallest item in the list.

Signup and view all the flashcards

List Comprehension

Creates a new list based on an existing list.

Signup and view all the flashcards

Nested List

A list inside another list. Useful with data representation.

Signup and view all the flashcards

Size of Nested List

Getting the number of sublists (outer list length) in a nested list using len().

Signup and view all the flashcards

Tuple

An immutable, ordered collection of items which can store different datatypes. Once a tuple is created, its values cannot be changed.

Signup and view all the flashcards

Creating a Tuple

Creation method using parentheses () with comma separated values.

Signup and view all the flashcards

Accessing Tuple Elements

Accessing elements by their position number.

Signup and view all the flashcards

Tuple Traversal

Iterating through each tuple element.

Signup and view all the flashcards

Slicing Tuples

Dividing a tuple into smaller tuples using the indexing method.

Signup and view all the flashcards

Searching Tuples

Looking for elements in a tuple

Signup and view all the flashcards

Length of Tuple

To find the length of a tuple, Python's function len()

Signup and view all the flashcards

List to Tuple

Converting a list to a tuple in Python

Signup and view all the flashcards

Built-in Tuple Methods

Built-in methods include count() and index().

Signup and view all the flashcards

re module

Used to work with regular expressions

Signup and view all the flashcards

Quantifiers

Specifies repetitions of patterns.

Signup and view all the flashcards

dict

The simplest way to create a dictionary

Signup and view all the flashcards

Modify Dictionnary

Assign value in a new key in a dictionary

Signup and view all the flashcards

keys:

Returning object to display all keys

Signup and view all the flashcards

Study Notes

  • Module 3 covers Sequences, Sets, Dictionaries, and Regular Expressions in Python.

Python Lists

  • Lists store sequences of various data types and are collections of different kinds of values.
  • Lists are mutable, allowing changes to their elements after creation.
  • Commas and square brackets separate and enclose list items.

Characteristics of Lists

  • Lists represent a group of individual objects as a single entity.
  • List elements are enclosed in square brackets and separated by commas e.g., a=[34,22,65,11].
  • Lists preserve insertion order.
  • Duplicate objects Lists allow duplicate objects.

Heterogeneous Lists

  • Lists can contain heterogeneous objects, example: a.append('python'), adding a string to a list of numbers.
  • Lists are dynamic, which means that their size can increase or decrease.
  • Positive and negative indexing is allowed allowing access from left-to-right or right-to-left.
  • List objects are mutable, meaning their content can change.

Creating a List

  • Lists can be created by placing elements inside square brackets and separating them with commas e.g., list1 = [1, 2, "Python", "Program", 15.9].

List Indexing and Splitting

  • List indexing operates similarly to string processing, utilizing the slice operator [].
  • Indexes range from 0 to the list's length minus 1.
  • The 0th index stores the first element, the 1st index stores the second element, and so on.
  • With list_variable(start: stop: step), specify a sub-list, where "start" is the beginning record position, "stop" is the last record position and "step" skips elements in between

Negative Indexing

  • Python supports negative indexing, counting from the right.
  • -1 represents the last element, -2 the second-to-last, and so on.

Inserting Elements into a List

  • append() adds an element to the end of the list.
  • extend() adds multiple elements to the end of the list.
  • insert() adds an element at a specific position.

Updating Elements in a List

  • List mutability means elements at specific indexes can be changed by assigning a new value to that index.
  • Multiple elements can also be updated using slicing.

Deleting Elements from a List

  • del deletes an element at a specified index.
  • remove() removes the first occurrence of a specific element.
  • pop() removes and returns the element at a specified index, defaulting to the last element.
  • clear() removes all elements from the list.
  • remove() is used to remove a specified item

Sorting Elements of a List

  • Lists are sorted using sort() (modifies the original list) or sorted() (returns a new sorted list).
  • Both functions support ascending or descending order and custom sorting criteria via the key argument.
  • sort() sorts alphanumerically, ascending, by default and is case-sensitive, sorting uppercase letters before lowercase.
  • To sort descending, use the keyword argument reverse = True.

Additional Methods

  • index() returns the index of the first occurrence of a value.
  • count() returns the number of occurrences of a value.
  • reverse() reverses the order of elements in the list.

List Operations

  • Concatenation (+) and repetition (*) work similarly to strings.
  • Additional list operations include: repetition, concatenation, length, iteration, and membership.
  • Repetition empowers the rundown components to be rehashed on different occasions

List Functions

  • len() calculates the length of the list.
  • max() returns the maximum element of the list.
  • min() returns the minimum element of the list.

List Comprehension

  • List comprehension offers a shorter way to create new lists based on existing list values.
  • For example, create a new list containing only the fruits with the letter ‘a’ in the name e.g., newlist = [x for x in fruits if "a" in x]

List Comprehension Syntax

  • [expression for item in iterable if condition]
  • expression is the transformation or value to be included in the new list.
  • item is the current element from the iterable.
  • iterable is a sequence or collection (e.g., list, tuple, set).
  • if condition is an optional filtering condition that decides whether the current item should be included.

List Comprehension Examples

  • A simple list comprehension to create a list of squares of numbers: squares = [x ** 2 for x in range(5)] , the output is [0, 1, 4, 9, 16]
  • Apply string operations using list comprehensions words = ["hello", "world", "python", "is", "great"] lengths = [len(word) for word in words], the output is [5, 5, 6, 2, 5]
  • Add a condition even_numbers = [x for x in range(10) if x % 2 == 0], the output is [0, 2, 4, 6, 8] and apply functions or methods: upper_words = [word.upper() for word in words], the output is ['HELLO', 'WORLD', 'PYTHON']
  • Create another list comprehension: matrix = [[1, 2, 3], [4, 5, 6], [7, 8, 9]] and flattened = [item for row in matrix for item in row], the output is [1, 2, 3, 4, 5, 6, 7, 8, 9]

Advantages of List Comprehensions

  • They are concise and readable, creating lists in a single line.
  • Offer faster execution due to internal optimizations in Python.
  • This supports the functional programming paradigm..

Nested Lists

  • A nested list in Python is a list that contains other lists as its elements, creating a multi-dimensional array-like structure.
  • Nested lists are useful for matrices, grids, or any hierarchically structured data.

Creating Nested Lists

  • Create a nested list by including lists inside another list e.g., nested_list = [[1, 2, 3], [4, 5, 6], [7, 8, 9]]
  • Lists can be arbitrarily nested.
  • Nested lists can be of different sizes and dimensions.

Accessing Elements in Nested Lists

  • Use multiple indices to access elements, where the first index refers to the outer list, and the second (or further) refers to the inner lists.
  • Update a single element e.g., nested_list[1][0] = 10 or update a sublist nested_list[1] = ['a', 'b', 'c'].

Iterating Over Nested Lists

  • Loop through nested lists using nested loops.
  • You can also use list comprehensions for flattening or extracting elements from nested lists.

Common Use Cases of Nested Lists

  • Represent matrices and grids (2D grids).
  • They can be used to represent more complex structures, such as multi-level categories or hierarchical data.

Common Operations on Nested Lists

  • Use len() to get the number of sublists.
  • Access all elements via list comprehension e.g., all_elements = [item for sublist in nested_list for item in sublist].
  • Transposing a matrix means swapping rows with columns using list comprehension or built-in functions like zip().
  • check if an element exists using a loop or conditional logic.

Multi-level Nested Lists

  • Extends beyond two levels to create multi-dimensional data structures.

Tuples in Python

  • Tuples are immutable, ordered collections of items, defined using parentheses and can store items of any data type.
  • Tuples prevent data modification during program execution.

Characteristics of Tuples

  • Similar to lists, tuples are ordered and elements are accessed using index values.
  • Items are immutable.
  • tuples cannot be appended, extended, or removed.

Creating Tuples

  • Create tuples by placing comma-separated values inside parentheses e.g., t = (10, 20, 30).
  • Parentheses are not strictly required when defining a tuple with a single element, but a trailing comma is required e.g., single_element_tuple = (10,).
  • Tuples can be created without parentheses.
  • Data types can be mixed e.g., mixed_tuple = (1, "hello", 3.14, True).

Accessing Tuple Elements

  • Tuples support indexing from 0, and also negative indexing.
  • They can be accessed using positive or negative indexing or you can use slice print(t[2:5]) or a while loop, or a for loop,

Traversing Items

  • You can also traverse a tuple using a for loop.

Slicing Tuples

  • Slicing divides a tuple into smaller tuples using the indexing method e.g., (0,1, 2, 3) t[1:]
  • The sliced tuple can include reverse indexing print(t[::-1])
  • Or elements from index 2 to 4 print(t[2:4])

Searching Elements in a Tuple

  • Search for elements even though tuples are immutable with in and index().
  • This in example checks for element existence in a tuple e.g., print(3 in my_tuple).
  • The index() example checks element position e.g., print(my_tuple.index(30)).

Modifying a Tuple

  • You can create a new tuple by concatenating existing elements e.g., (my_tuple[:1] + (4,) + my_tuple[2:])

Deleting a Tuple

  • In Python, to delete a tuple, use the del keyword.
  • After deleting the tuple, you will get a 'NameError' if you try to access it.
  • It's no possible to remove individual elements only the whole tuple.

Finding Tuple Length

  • Python's len() function retrieves the length of a tuple.

Multiple Data Types

  • Tuples support elements with multiple data types.

Sorting

  • Tuples lack a sort() method due to immutability.
  • You can use Python's built-in sorted() function to sort.

Nested Tuples

  • Can contain other tuples to create multi-dimensional structures.

Tuple Operations

  • You cane concatenate and repeat tuples.

Converting Lists

  • Can convert a list to a tuple using tuple().

Tuple Methods

  • While tuples are immutable and lack list-like methods, they include built-in methods.
  • count(x) returns occurrences.
  • index(x) returns the index.

Strings in Python

  • Strings are collections of characters surrounded by single, double, or triple quotes.

Creating Strings

  • Strings are created by enclosing characters in single or double quotes, but triple quotes are generally used for multiline strings or docstrings.

String indexing and splitting

  • Indexing strings follows the same logic as indexing other data structures in Python e.g., str[0] = 'H'.
  • You can slice a string into smaller parts e.g., str[2:4] # prints II

String Operations

  • Concatenation combines strings using the + operator.
  • Repetition repeats a string multiple times using the * operator.
  • Indexing accesses characters using their index starting from 0
  • Slicing extracts a substring using str[start:end].
  • To get the number of characters in a string use len().
  • To check whether a substring exists, use in or not in

String Formatting

  • Python's escape sequences, denoted by a backslash, handle special characters within strings.
  • Common escape sequences include \newline, \\, \', \", \a, \b, \f, \n, \r, \t, \v.
  • The format() method uses curly braces as placeholders to insert values and the operator % binds values with format specifiers

String Handling Methods

  • to lowercase: lower()
  • to uppercase: upper()
  • Capatalizes the first letter capitalize()
  • Capitalizes first letter of each word in the string title()
  • Removes leading or trailing white space strip()
  • Replaces a substring replace()
  • Finds a substring find()
  • Splits strings into a list based on default white space split()
  • It joins strings with a specified parameter join()
  • Checks if string starts or ends with these characters startswith() and endswith()

Sets In Python

  • Sets are unordered collections of unique elements, commonly used to store multiple items without specific order.

Sets Characteristics

  • Each element in a set is unique and can be of any immutable data type.
  • Sets are mutable, allowing addition or removal of elements in Python.
  • Duplicates are not allowed but heteroegenous elements are
  • Mathematical operations like Union, Intersection, Difference can be appleid.

Set Creation

  • Sets can be created by curly braces e.g., my_set = {1, 2, 3, 4, 5}.
  • Sets can be created by a set()constuctor e.g., my_set = set([1, 2, 3, 4, 5]).
  • You can create an empty set with the set() constuctor e.g., empty_set = set()

Adding Elements

  • Adds a single element with the add() methos e.g,. my_set.add(4).

Removing Elements

  • Removes a specific elmement with the remove() method
  • The discard() method removes an element if exist but wont raise an error if the element cant be found
  • pop() removes or returns an arbotrary element from the list.
  • clear removes all elements

Set Operations

  • Python allows several mathematical operations on sets: -Union | or union() -Intersection & or intersection() -Difference () or difference() -Symmetric Difference or symmetric_difference():

Subset and Superset

  • the issubset() methods checks where the subsets and supersets are available.
  • isdisjoint() checks if two sets have nothign in common

Set Comprehension

  • Set comprehension is similar to list comprehension. It's a concise way to create sets by applying expressions to iterate over an iterable e.g., my_set = {x for x in range(1, 6) if x % 2 == 0}

Dictionaries in Python

  • Dictionaries are unordered collections of key-value pairs, each key must be unique value can be of any data type, and dictionaries are mutable.

Creating a Dictionary

  • Use curly braces {} , my_dict = {"name": "Alice", "age": 25, "city": "New York"}
  • You can use the dict() constructor, by passing the key and values, my_dict = dict(name="Alice", age=25, city="New York")
  • A list of tuples my_dict = dict([("name", "Alice"), ("age", 25), ("city", "New York")])

Operations on Dictionaries

  • Use square brackets name = my_dict["name"] or functions to access an object
  • For operations like adding, assigning key values, removing key values e.g., assigning key values my_dict["address"] = "123 Main St"
  • Use del to remeove a value from a dict key e.g., del my_dict["address"]
  • Use functions like pop() and clear()

Dictionary Methods

  • keys() returns a view of all keys.
  • values() returns a view of all values.
  • items() returns a view of all key-value pairs.
  • update() merges elements from another dictionary e.g., new_data or with key-value pairs.
  • setdefault() adds a key with a default value if it doesn't exist.
  • fromkeys() creates another dictionary with some values

Sorting

  • Dictionaries can be sorted by keys or by values with a lambda expression

Regular Expressions in Python

  • Regex are powerful tools used for pattern matching and searching within strings and the re module in Python is used for regular expressions in text processing tasks like validating input.

Regular Expression Operations

  • Define operations using a re module
  • Set import re to import modules
  • The syntax follows using r which follows basic special characters to find and match texts

Regex Functions

  • findall Returns a list containing all matches
  • search Returns a Match object if there is a match anywhere in the string
  • split Returns a list where the string has been split at each match
  • sub Replaces one or many matches with a string

Sequence Characters

  • Sequence characters form simple patterns to match parts of text.
  • Literal characters simply find exact characters
  • The dot matches anything except new lines
  • ^Caret finds the beginning of a string
  • $ Dollar Sign finds the end of a string
  • And [] specifies type of character

Quantifiers

  • Quantifiers define the repetition of patterns
    • Asterisk: Matches zero or more occurrences
    • Plus: Matches one or more occurrences
  • ? Question Mark: Matches zero or one occurrence
  • {n,m}: Matches a specified range of occurrences

Special Character sets

  • \ Backslash is used to escape special characters
  • . The dot matches any character except new lines
  • Common character classes include \d, \w, \s
  • ^or $ are Anchors. Use re.search()
  • Use parantheses to group elements ()
  • Use pipes to add alternates to items

Studying That Suits You

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

Quiz Team

Related Documents

More Like This

Python Lists Creation Quiz
3 questions

Python Lists Creation Quiz

DurableExtraterrestrial avatar
DurableExtraterrestrial
Python Lists
10 questions

Python Lists

MarvellousColumbus8275 avatar
MarvellousColumbus8275
Python Programming: Data Structures
20 questions
Use Quizgecko on...
Browser
Browser