0% found this document useful (0 votes)
8 views23 pages

Lists and Dictionaries: The Hangman Game: Tamal Das CSE, IIT Dharwad

The document outlines a chapter on the Hangman game, focusing on data structures such as lists, dictionaries, and sets in Python. It covers various operations and methods associated with these data structures, including creating, accessing, modifying, and understanding their properties. The chapter concludes with a summary of key concepts related to lists, dictionaries, sets, shared references, and nested sequences.

Uploaded by

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

Lists and Dictionaries: The Hangman Game: Tamal Das CSE, IIT Dharwad

The document outlines a chapter on the Hangman game, focusing on data structures such as lists, dictionaries, and sets in Python. It covers various operations and methods associated with these data structures, including creating, accessing, modifying, and understanding their properties. The chapter concludes with a summary of key concepts related to lists, dictionaries, sets, shared references, and nested sequences.

Uploaded by

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

Lists and Dictionaries:

The Hangman Game


Tamal Das
CSE, IIT Dharwad
Outline – Chapter 5
• Introducing the Hangman Game
• Using Lists
• Using List Methods
• Understanding When to Use Tuples Instead of Lists
• Using Nested Sequences
• Understanding Shared References
• Using Dictionaries
• Back to the Hangman Game
• Summary
Dec 9, 2024 Introduction to Programming 2
Introducing the
Hangman Game
hangman.py

Dec 9, 2024 Introduction to Programming 3


Introducing the
Hangman Game
hangman.py

Dec 9, 2024 Introduction to Programming 4


Introducing the
Hangman Game
hangman.py

Dec 9, 2024 Introduction to Programming 5


Using Lists
Introducing the Hero’s Inventory 3
• hero's_inventory3.py
Creating a List
Using the len() Function with Lists
Using the in Operator with Lists
Indexing Lists
Slicing Lists
Concatenating Lists

Dec 9, 2024 Introduction to Programming 6


Understanding
List Mutability
Assigning a New List Element by Index
• Can’t create a new element in this way
Assigning a New List Slice
Deleting a List Element
Deleting a List Slice

Dec 9, 2024 Introduction to Programming 7


thislist = ["apple", "banana", "cherry"]
if "apple" in thislist:
print("Yes, 'apple' is in the fruits list")

# changing items
thislist = list(["apple", "banana", "cherry", "orange", "kiwi", "mango"])

Lists thislist[1:3] = ["blackcurrant"]


thislist[1:3] = ["blackcurrant", "watermelon"]
Used to store multiple items in a single
thislist[1:3] = ["blackcurrant", "watermelon", "chikoo"]
variable
Enclosed in square brackets, i.e. […] # inserting items
thislist.insert(2, "watermelon")
list() constructor
Accessed using indexes # appending items
thislist.append('watermelon')
• Positive as well as negative
Slicing applicable # extending a list
thistuple = ("kiwi", "orange")
• Similar to strings thislist.extend(thistuple)
print(thislist + thislist)
Changing items
Inserting items # removing an item
thislist.remove("watermelon")
Appending items
Extending a list # pop
print(thislist.pop(1))
Removing items print(thislist.pop())
Dec 9, 2024
Poping and deleting items Introduction to Programming 8
# deleting an item
# looping through a list by element or index
for x in thislist:
print(x, end="\t")
print()

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

Sorting # list comprehension


print([x for x in thislist])
Copying
# sorting
thislist.sort(key=lambda x:len(x), reverse = True)
thislist.sort(key=lambda x:x.lower(), reverse = True)

# 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

Dec 9, 2024 Introduction to Programming 10


Understanding When to Use Tuples
Instead of Lists
• Tuples are
• faster than lists
• better suited for static/constant data

Dec 9, 2024 Introduction to Programming 11


Using Nested Sequences
# Creating Nested Sequences
nested = ["first", ("second", "third"), ["fourth", "fifth", "sixth"]]
scores = [("Moe", 1000), ("Larry", 1500), ("Curly", 3000)]
nested = ("deep", ("deeper", ("deepest", "still deepest")))

# Accessing Nested Elements


print(scores[1])
print(scores[2][0])

# Unpacking a Sequence
name, score = ("Shemp", 175)

Dec 9, 2024 Introduction to Programming 12


Using Nested
Sequences
Introducing the High Scores 2
• high_scores2.py
Setting Up the Program
Displaying the Scores
• by Accessing Nested Tuples
Adding a Score
• by Appending a Nested Tuple
Dealing with an Invalid Choice
Waiting for the User

Dec 9, 2024 Introduction to Programming 13


Understanding mike = ["khakis", "dress shirt", "jacket"]
Shared mr_dawson = mike
honey = mike
References print(mike)
Be aware of shared references print(mr_dawson)
when using mutable values print(honey)
honey[2] = "red sweater"
• If you change the value through one print(honey)
variable, it will be changed for all. print(mike)
print(mr_dawson)

mike = ["khakis", "dress shirt", "jacket"]


honey = mike[:] # honey does not refer to
the same list as mike, but its copy.
honey[2] = "red sweater"
print(honey)
print(mike)

Dec 9, 2024 Introduction to Programming 14


thisdict = {
"brand": "Ford",
"model": "Mustang",
"year": 1964
}

# 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()

Dec 9, 2024 Introduction


# todelete
Programming dictionary 16
Using Dictionaries
• Creating Dictionaries
• Accessing Dictionary Values
• Using a Key to Retrieve a Value
• Testing for a Key with the in Operator Before Retrieving a Value
• Using the get() Method to Retrieve a Value
• Understanding Dictionary Requirements
• Keys must be unique and immutable

Dec 9, 2024 Introduction to Programming 17


Using Dictionaries
Introducing the Geek Translator Program
• geek_translator.py
Setting Up the Program
Getting a Value
Adding a Key-Value Pair
Replacing a Key-Value Pair
Deleting a Key-Value Pair
• Deleting a non-existent key results in an
error
Wrapping Up the Program

Dec 9, 2024 Introduction to Programming 18


# set() constructor; note the double round-brackets
thisset = set(("apple", "banana", "cherry"))

# 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())

Sets # loop through sets


for x in thisset:
pop() print(x)
Looping through sets # join sets - union, intersection, symmetric_difference
Join sets y = {"google", "microsoft", "apple"}
print(thisset.union(y))
• Contains unique elements print(thisset.intersection(y))
print(thisset.symmetric_difference(y))
Clear set
Delete set # clear set
thisset.clear()

# delete set
del thisset

Dec 9, 2024 Introduction to Programming 20


Collections

Collections Mutable? Changeable? Duplicates Ordered? Mixed


allowed? data types?

Lists Yes Yes Yes Yes Yes

Sets Yes No No No Yes

Tuples No No Yes Yes Yes

Dictionaries Yes Yes No Yes Yes

Dec 9, 2024 Introduction to Programming 21


Back to the Hangman Game
• Setting Up the Program
• Creating Constants
• Initializing the Variables
• Creating the Main Loop
• Getting the Player’s Guess
• Checking the Guess
• Ending the Game

Dec 9, 2024 Introduction to Programming 22


Summary
• Lists
• Dictionaries
• Sets
• Shared references
• Nested Sequences

Dec 9, 2024 Introduction to Programming 23

You might also like

pFad - Phonifier reborn

Pfad - The Proxy pFad of © 2024 Garber Painting. All rights reserved.

Note: This service is not intended for secure transactions such as banking, social media, email, or purchasing. Use at your own risk. We assume no liability whatsoever for broken pages.


Alternative Proxies:

Alternative Proxy

pFad Proxy

pFad v3 Proxy

pFad v4 Proxy