Lists and Dictionaries: The Hangman Game: Tamal Das CSE, IIT Dharwad
Lists and Dictionaries: The Hangman Game: Tamal Das CSE, IIT Dharwad
# changing items
thislist = list(["apple", "banana", "cherry", "orange", "kiwi", "mango"])
for i in range(len(thislist)):
print(thislist[i], end="\t")
print()
Lists i = 0
while i < len(thislist):
Looping through a list by index/item print(thislist[i])
List comprehension i = i + 1
# copying
list2 = thislist
thislist.pop()
mylist = thislist.copy()
print(mylist)
mylist = list(thislist)
print(mylist)
# clearing lists
Dec 9, 2024 Introduction to Programming
thislist.clear() 9
print(thislist)
Using List
Methods
Introducing the High Scores Program
• high_scores.py
Setting Up the Program
Displaying the Menu
Exiting the Program
Displaying the Scores
Adding a Score
Removing a Score
Sorting the Scores
Dealing with an Invalid Choice
Waiting for the User
# Unpacking a Sequence
name, score = ("Shemp", 175)
# access items
Dictionaries x = thisdict["model"]
x = thisdict.get("model")
Enclosed in curly braces, i.e. {…}
# get list of keys, values, items
dict() constructor thisdict.keys()
thisdict.values()
Accessing items
thisdict.items()
Checking existence of a key
# check existence of a key
Change values print("model" in thisdict)
Adding/removing items
# change values
thisdict["year"] = 2018
thisdict.update({"year": 2020})
# adding item
thisdict["color"] = "red"
# removing items
print(thisdict.pop("model"))
print(thisdict.popitem()) #removes the last inserted item
#del thisdict["model"]
Dec 9, 2024 Introduction to Programming 15
# loop through a dictionary
for x in thisdict:
print(x, thisdict[x])
for x in thisdict.values():
print(x)
Dictionaries
for x in thisdict.keys():
Looping through dictionaries
print(x)
Copying dictionaries
Clearing dictionaries for x, y in thisdict.items():
print(x, y)
Deleting dictionaries
# copy dictionaries
dict2 = thisdict
thisdict["year"] = 1965
print(dict2["year"])
print(thisdict.copy())
mydict = dict(thisdict)
# clear dictionary
thisdict.clear()
# access items
Sets for x in thisset:
print(x)
Enclosed in curly braces, i.e. {…}
print("banana" in thisset)
Set items are unchangeable, but you
can remove items and add new
items. # add items
set() constructor thisset.add("orange")
Access items
# add sets
Add items
mylist = ["kiwi", "orange"]
Add sets thisset.update(mylist)
Remove/discard items
# remove/discard items
thisset.remove("banana") # if not found, raises an error
thisset.discard("banana") # if not found, doesn't raise an
error
Dec 9, 2024 Introduction to Programming 19
# pops out different elements each time
print(thisset.pop())
# delete set
del thisset