Lecture 7 Collective Data Types (1)
Lecture 7 Collective Data Types (1)
INTRODUCTION TO COMPUTER
PROGRAMMING
• Example: Based on a list of fruits, you want a new list, containing only the
fruits with the letter "a" in the name.
LIST COMPREHENSION (CONTD)
• Example: Based on a list of fruits, you want a new list, containing only the
fruits with the letter "a" in the name.
MULTIDIMENSIONAL LISTS
• A list within another list is nested. There can be more than one
additional dimension to lists in Python. Keeping in mind that a list can
hold other lists, that basic principle can be applied over and over. Multi-
dimensional lists are the lists within lists.
LISTS VS TUPLES
• Lists work well for storing sets of items that can change throughout the
life of a program.
• However, sometimes you’ll want to create a list of items that cannot
change. That is where tuples come in.
• Python refers to values that cannot change as immutable, and an
immutable list is called a tuple.
• A tuple looks just like a list except you use parentheses instead of
square brackets.
• For example, if we have a rectangle that should always be a certain
size, we can ensure that its size doesn’t change by putting the
dimensions into a tuple:
DICTIONARY
• A dictionary is a key:value pair, similar to an associative array found in
other programming languages.
• A dictionary is like an address-book where you can find the address or
contact details of a person by knowing only his/her name i.e. we
associate keys (name) with values (details).
• Note that the key must be unique just like you cannot find out the
correct information if you have two persons with the exact same name.
• Unlike tuples, dictionaries are mutable.
TRAVERSING DICTIONARIES
The methods keys(), values() and items() are used to get views as
displayed below. A for-loop can be used to access single elements of
the views.
TRAVERSING DICTIONARIES
(CONTD)
DICTIONARY RESTRICTIONS
• First, a given key can appear in a dictionary only once. Duplicate keys are
not allowed.
• Secondly, a dictionary key must be of a type that is immutable. A tuple
can also be a dictionary key because tuples are immutable.
• Thus, neither a list nor another dictionary can serve as a dictionary key,
because lists and dictionaries are mutable.