Module Lists Dic Tuples
Module Lists Dic Tuples
DICTONARIES,
TUPLES & SETS
>>> Overview
LEARNING OUTCOMES
list.append(3) => [34, 21, 29, 86, 29, 3] list.remove(29) => [34, 21, 86, 29]
list.insert(2, 3) => [34, 21, 3, 29, 86] list.extend(list2) => [34, 21, 29,86, 29, 1, 2, 3, 4]
[0] * 5 => [0, 0, 0, 0, 0]
More Methods
More Methods
•list.count(element) – returns number of times element occurs in the list
•list.sort – sorts the element in place
•list.reverse – reverses the element in place
Length of lists
len(list) => 7
print “This list is ” + str(list1) => This list is *“elements”, “of”, “our”, “list”+
print “This list is ” + str(list2) => This list is [21, 29, 86, 19, 42]
Example:
range(5) => [0, 1, 2, 3, 4]
range(0, 10, 2) => [0, 2, 4, 6, 8]
Example: Example 2:
list = [3, 6, 5, 7, 15] list = [3, 6, 5, 7, 15]
for i in list: for i in range(len(list))
print i list[i] = list[i] + 1
Program to Dynamically Build User Input as a List
Using a for loop you can iterate through each item in a list.
Using a for loop you can iterate through each item in a list.
List = [ 5,4,3,2,1]
Write Python Program to Sort Numbers in a List in Ascending Order
Using Bubble Sort by Passing the List as an Argument to the Function Call
def bubble_sort(list_items):
for i in range(len(list_items)-1):
for j in range(len(list_items)-i-1):
if list_items[j] > list_items[j+1]:
temp = list_items[j]
list_items[j] = list_items[j+1]
list_items[j+1] = temp
print(f"The sorted list using Bubble Sort is {list_items}")
def main():
items_to_sort = [5, 4, 3, 2, 1]
bubble_sort(items_to_sort)
if name == " main ":
main()
Dictionaries
Creating Dictionary:
A dictionary is a collection of an unordered set of key:value pairs, with
the requirement that the keys are unique within a dictionary
Dictionaries are constructed using curly braces { }, wherein you
include a list of key:value pairs separated by commas
Also, there is a colon (:) separating each of these key and value pairs,
where the words to the left of the colon operator are the keys and the
words to the right of the colon operator are the values.
The syntax for creating a dictionary is,
Dictionaries
For example,
>>> fish = {"g": "goldfish", "s":"shark", "n": "needlefish",
"b":"barramundi", "m":"mackerel"}
>>> fish
{'g': 'goldfish', 's': 'shark', 'n': 'needlefish', 'b': 'barramundi', 'm':
'mackerel’-
In dictionaries, the order of key:value pairs does not matter. For example,
This indicates that the ordering of key:value pairs does not matter in
dictionaries.
Slicing in dictionaries is not allowed since they are not ordered like lists.
Accessing and Modifying key:value Pairs in Dictionaries
The syntax for modifying the value of an existing key or for adding a
new key:value pair to a dictionary is,
dictionary_name[key] = value
If the key is already present in the dictionary, then the key gets
updated with the new value.
If the key is not present then the new key:value pair gets added to the
dictionary.
Accessing and Modifying key:value Pairs in Dictionaries
Example:
>>> country = {"india":1305, "srilanka":1440,"china":1511,
"france":1480, "austria":1520}
>>> country["india"] = 1310
>>> country
{'india': 1310, 'srilanka': 1440, 'china': 1511, 'france': 1480, 'austria':
1520}
>>> country["china"]
1511
Since dictionaries are mutable, you can add a new key:value pair or
change the values for existing keys using the assignment operator.
The dict() Function
There are many built-in functions for which a dictionary can be passed as
an argument.
Built-In Functions Used on Dictionaries
For example,
>>> presidents = {"washington":1732, "jefferson":1751, "lincoln":1809,
"roosevelt":1858, "eisenhower":1890}
>>> len(presidents)
5
>>> all_dict_func = {0:True, 2:False}
>>> all(all_dict_func)
False
>>> all_dict_func = {1:True, 2:False}
>>> all(all_dict_func)
True
>>> any_dict_func = {1:True, 2:False}
>>> any(any_dict_func)
True
Built-In Functions Used on Dictionaries
Example continue…..
>>> sorted(presidents)
['eisenhower', 'jefferson', 'lincoln', 'roosevelt', 'washington']
>>> sorted(presidents, reverse = True)
['washington', 'roosevelt', 'lincoln', 'jefferson', 'eisenhower']
>>> sorted(presidents.values())
[1732, 1751, 1809, 1858, 1890]
>>> sorted(presidents.items())
[('eisenhower', 1890), ('jefferson', 1751), ('lincoln', 1809), ('roosevelt',
1858), ('washington', 1732)]
Dictionary Methods
vowels = dict.fromkeys(keys)
print(vowels)
{'a': None, 'u': None, 'o': None, 'e': None, 'i': None}
Output
{'a': 'vowel', 'u': 'vowel', 'o': 'vowel', 'e': 'vowel', 'i': 'vo
original_marks = {'Physics':67, 'Maths':87}
copied_marks = original_marks.copy()
element = sales.pop('apple')
n=person.setdefault('name')
print(n)
salary = person.setdefault('salary')
age = person.setdefault('age', 22)
print(person)
output:Phill
person = {'name': 'Phill', 'age': 22, 'salary': None}
Populating Dictionaries with key:value Pairs
countries = {}
countries.update({"Asia":"India"})
countries.update({"Europe":"Germany"})
countries.update({"Africa":"Sudan"})
countries
{'Asia': 'India', 'Europe': 'Germany', 'Africa': 'Sudan'}
Program to Dynamically Build User Input as a List
def main():
print("Method 1: Building Dictionaries")
build_dictionary = {}
for i in range(0, 2):
dic_key = input("Enter key ")
dic_val = input("Enter val ")
build_dictionary.update({dic_key: dic_val})
print(f"Dictionary is {build_dictionary}")
print("Method 2: Building Dictionaries")
build_dictionary = {}
for i in range(0, 2):
dic_key = input("Enter key ")
dic_val = input("Enter val ")
build_dictionary[dic_key] = dic_val
print(f"Dictionary is {build_dictionary}")
print("Method 3: Building Dictionaries")
build_dictionary = {}
i=0
while i < 2:
dict_key = input("Enter key ")
dict_val = input("Enter val ")
build_dictionary.update({dict_key: dict_val})
i=i+1
print(f"Dictionary is {build_dictionary}")
if name == " main ":
main()
Traversing of Dictionary
A for loop can be used to iterate over keys or values or key:value pairs in
dictionaries
If you iterate over a dictionary using a for loop, then, by default, you will
iterate over the keys.
The dict_keys, dict_values,and dict_items data types returned by
dictionary methods can be used in for loops to iterate over the keys or
values or key:value pairs.
Program to Illustrate Traversing of key:value Pairs in Dictionaries
Using for Loop
To delete the key:value pair, use the del statement followed by the name of
the dictionary along with the key you want to delete.
You can store any item of type string, number, object, another variable, and
even another tuple itself. You can have a mix of different types of items in
tuples, and they need not be homogeneous.
Both start and stop are integer values (positive or negative values). Tuple
slicing returns a part of the tuple from the start index value to stop index
value, which includes the start index value but excludes the stop index
value. The step specifies the increment value to slice by and it is optional.
Indexing and Slicing in Tuples
Example:
For example,
>>> years = (1987, 1985, 1981, 1996)
>>> len(years)
4
>>> sum(years)
7949
>>> sorted_years = sorted(years)
>>> sorted_years
[1981, 1985, 1987, 1996]
Relation between Tuples and Lists
Tuples are immutable, and usually, contain a heterogeneous sequence of
elements that are accessed via unpacking or indexing.
Lists are mutable, and their items are accessed via indexing. Items cannot
be added, removed or replaced in a tuple.
For example,
3 The list is better for performing operations, such Tuple data type is appropriate for accessing
as insertion and deletion. the elements
5 Lists have several built-in methods Tuple does not have many built-in methods.
For example,
>>> channels = ("ngc", "discovery", "animal_planet", "history", "ngc")
>>> channels.count("ngc")
2
>>> channels.index("history")
Write Python Program to Swap Two Numbers Without Using
Intermediate/Temporary Variables. Prompt the User for Input
def main():
a = int(input("Enter a value for first number "))
b = int(input("Enter a value for second number "))
b, a = a, b
print("After Swapping")
print(f"Value for first number {a}")
print(f"Value for second number {b}")
if name == " main ":
main()
Sets
A set is an unordered collection with no duplicate items.
Primary uses of sets include membership testing and eliminating
duplicate entries.
Sets also support mathematical operations, such as union, intersection,
difference, and symmetric difference.
Sets
For example,
1. >>> european_flowers = {"sunflowers", "roses", "lavender", "tulips", "goldcrest"}
2. >>> american_flowers = {"roses", "tulips", "lilies", "daisies"}
3. >>> american_flowers.add("orchids")
4. >>> american_flowers.difference(european_flowers)
{'lilies', 'orchids', 'daisies'}
5. >>> american_flowers.intersection(european_flowers)
{'roses', 'tulips'}
6.>>> american_flowers.isdisjoint(european_flowers)
False
7.>>> american_flowers.issuperset(european_flowers)
False
8.>>> american_flowers.issubset(european_flowers)
False
9. >>> american_flowers.symmetric_difference(european_flowers)
{'lilies', 'orchids', 'daisies', 'goldcrest', 'sunflowers', 'lavender'}
Traversing of Sets
You can iterate through each item in a set using a for loop.
Output:
hms_beagle is a Warship
u.s.s._arizona is a Warship
ins_airavat is a Warship
ins_hetz is a Warship
map function
reduce function
filter function