[go: up one dir, main page]

0% found this document useful (0 votes)
33 views36 pages

Module04-Lists Tuples Sets and Dictionaries

This document provides an overview of lists, tuples, sets, and dictionaries in computer programming. It discusses the key characteristics and functions of each data type, including: - Tuples are immutable sequences that can contain heterogeneous data. Lists are mutable sequences that can be modified. - Sets contain unique elements and support mathematical operations like union, intersection, and difference. - Dictionaries contain (key, value) pairs and are indexed by unique keys for fast lookup. Keys must be immutable.

Uploaded by

efeerer582
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
33 views36 pages

Module04-Lists Tuples Sets and Dictionaries

This document provides an overview of lists, tuples, sets, and dictionaries in computer programming. It discusses the key characteristics and functions of each data type, including: - Tuples are immutable sequences that can contain heterogeneous data. Lists are mutable sequences that can be modified. - Sets contain unique elements and support mathematical operations like union, intersection, and difference. - Dictionaries contain (key, value) pairs and are indexed by unique keys for fast lookup. Keys must be immutable.

Uploaded by

efeerer582
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 36

Computer Programming I

Binnur Kurt, PhD

binnur.kurt@rc.bau.edu.tr

MODULE 4
LISTS, TUPLES, SETS, AND DICTIONARIES
TUPLE

Tuple
> Tuples are immutable and typically store heterogeneous data, but the data can
be homogeneous.
> A tuple’s length is its number of elements and cannot change during program
execution.
Tuple

Tuple
LIST

List
Empty List

Creating a List
Creating a List

Creating a List
Creating a List

List
> Lists , like tuples, are sequences that contain elements referenced starting at
zero.
> The individual elements of a list can be accessed in the same way as tuples.
List
> You reference a list element by writing the list’s name followed by the
element’s index enclosed in square brackets

Accessing Elements from the end with Negative Indices


> Lists also can be accessed from the end by using negative indices:
Lists Are Mutable
> Lists are mutable—their elements can be modified:

List: Examples (1/3)


List: Examples (2/3)

List: Examples (3/3)


Unpacking Sequences
> You can unpack any sequence’s elements by assigning the sequence to a
comma-separated list of variables

Swapping Values Via Packing and Unpacking


> You can swap two variables’ values using sequence packing and unpacking
Accessing Indices and Values Safely with enumerate
> The preferred mechanism for accessing an element’s index and value is the
built-in function enumerate.
> This function receives an iterable and creates an iterator that, for each
element, returns a tuple containing the element’s index and value.

Accessing Indices and Values Safely with enumerate


Sequence Slicing
> You can slice sequences to create new sequences of the same type containing
subsets of the original elements.
> Slice operations can modify mutable sequences—those that do not modify a
sequence work identically for lists, tuples and strings

Sequence Slicing
Slicing with Steps
> The following code uses a step of 2 to create a slice with every other element
of numbers

> You can use a negative step to select slices in reverse order.

Modifying Lists Via Slices


> You can modify a list by assigning to a slice of it—the rest of the list is
unchanged.
> The following code replaces numbers’ first three elements, leaving the rest
unchanged:

> The following deletes only the first three elements of numbers by assigning an
empty list to the three-element slice:
Modifying Lists Via Slices
> The following assigns a list’s elements to a slice of every other element of
numbers:

Modifying Lists Via Slices


> Let’s delete all the elements in numbers, leaving the existing list empty:
Modifying Lists Via Slices
> Deleting numbers’ contents is different from assigning numbers a new empty
list [] (snippet [22]).
> To prove this, we display numbers’ identity after each operation.
> The identities are different, so they represent separate objects in memory:

del Statement
> The del statement also can be used to remove elements from a list and to
delete variables from the interactive session.
> You can remove the element at any valid index or the element(s) from any valid
slice.
> Let’s create a list, then use del to remove its last element:
del Statement
> The following deletes the list’s first two elements:

> The following uses a step in the slice to delete every other element from the
entire list:

del Statement
> The following code deletes all the list’s elements:
Sorting a List in Ascending Order
> A common computing task called sorting enables you to arrange data either in
ascending or descending order.
> List method sort modifies a list to arrange its elements in ascending order

Sorting a List in Descending Order


> To sort a list in descending order, call list method sort with the optional
keyword argument reverse set to True (False is the default):
Built-In Function sorted
> Built-in function sorted returns a new list containing the sorted elements of
its argument sequence—the original sequence is unmodified.

Key Functions
> Both list.sort() and sorted() have a key parameter to specify a function to be
called on each list element prior to making comparisons.
Key Functions

Searching Sequences
> Often, you’ll want to determine whether a sequence (such as a list, tuple or
string) contains a value that matches a key value.
> Searching is the process of locating a key.
> List method index takes as an argument a search key—the value to locate in
the list—then searches through the list from index 0 and returns the index of
the first element that matches the search key:
Searching Sequences

Specifying the Starting Index of a Search


Operators in and not in
> Operator in tests whether its right operand’s iterable contains the left
operand’s value:

Using Operator in to prevent a ValueError


SET

Set
> A set is an unordered collection of unique values.
> Sets may contain only immutable objects, like strings, ints, floats and tuples
that contain only immutable elements.
> Sets are iterable
> They are not sequences and do not support indexing and slicing with square
brackets, [].
– Dictionaries also do not support slicing.
Set
> The following code creates a set of strings named colors:

> Notice that the duplicate string 'red' was ignored without causing an error

Checking Whether a Value Is in a Set


> You can check whether a set contains a particular value using the in and not in
operators:
Iterating Through a Set
> Sets are iterable, so you can process each set element with a for loop:

Comparing Sets
> The < operator tests whether the set to its left is a proper subset of the one to
its right
Mathematical Set Operations: Union
> The union of two sets is a set consisting of all the unique elements from both
sets.
> You can calculate the union with the | operator or with the set type’s union
method:

Mathematical Set Operations: Intersection


> The intersection of two sets is a set consisting of all the unique elements that
the two sets have in common.
> You can calculate the intersection with the & operator or with the set type’s
intersection method:
Mathematical Set Operations: Difference
> The difference between two sets is a set consisting of the elements in the left
operand that are not in the right operand.
> You can calculate the difference with the - operator or with the set type’s
difference method:

Mathematical Set Operations: Symmetric Difference


> The symmetric difference between two sets is a set consisting of the elements
of both sets that are not in common with one another.
> You can calculate the symmetric difference with the ^ operator or with the set
type’s symmetric_difference method:
Mathematical Set Operations: Disjoint
> Two sets are disjoint if they do not have any common elements.
> You can determine this with the set type’s isdisjoint method:

Mutable Mathematical Set Operations


> Mutable Mathematical Set Operations like operator |, union augmented
assignment |= performs a set union operation, but |= modifies its left
operand:
Mutable Mathematical Set Operations
> The other mutable set methods are:
– intersection augmented assignment &=
– difference augmented assignment -=
– symmetric difference augmented assignment ^=
> Their corresponding methods with iterable arguments are:
– intersection_update
– difference_update
– symmetric_difference_update

Methods for Adding and Removing Elements from Set


> Set method add inserts its argument if the argument is not already in the set;
otherwise, the set remains unchanged:
Methods for Adding and Removing Elements from Set
> Set method remove removes its argument from the set—a KeyError occurs if
the value is not in the set
> Set method discard also removes its argument from the set but does not
cause an exception if the value is not in the set.

Methods for Adding and Removing Elements from Set


> Set method discard also removes its argument from the set but does not
cause an exception if the value is not in the set.
DICTIONARY

Dictionary
> A dictionary is like lists and tuples.
> It is another type of container for a group of data.
> Lists are indexed by their numeric order
> Dictionaries are indexed by names that you choose.
> These names can be letters, numbers, strings, or symbols — whatever suits
you.
Unique Keys
> A dictionary’s keys must be immutable (such as strings, numbers or tuples) and
unique (that is, no duplicates).
> Multiple keys can have the same value, such as two different inventory codes
that have the same quantity in stock.

Dictionary
Dictionary

Dictionary
Dictionary

Dictionary
Converting Dictionary Keys, Values, and Pairs to Lists

Processing Keys in Sorted Order


Iterating through a Dictionary

Standard Library Module collections

You might also like