0% found this document useful (0 votes)
102 views

Unpack A Collection: "Orange" "Banana" "Cherry"

This document provides examples of various operations that can be performed on lists in Python. It demonstrates how to create lists, access list items by index, slice lists, modify lists by adding, removing, and updating items, loop through lists, use list comprehension for shorter looping syntax, and more. The key takeaways are that lists are ordered, mutable sequences that can contain heterogeneous data types and support various methods for common list operations like append, insert, pop, remove and more.

Uploaded by

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

Unpack A Collection: "Orange" "Banana" "Cherry"

This document provides examples of various operations that can be performed on lists in Python. It demonstrates how to create lists, access list items by index, slice lists, modify lists by adding, removing, and updating items, loop through lists, use list comprehension for shorter looping syntax, and more. The key takeaways are that lists are ordered, mutable sequences that can contain heterogeneous data types and support various methods for common list operations like append, insert, pop, remove and more.

Uploaded by

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

x, y, z = 

"Orange", "Banana", "Cherry"
print(x)
print(y)
print(z)

Unpack a Collection
If you have a collection of values in a list, tuple etc. Python allows you to
extract the values into variables. This is called unpacking.

fruits = ["apple", "banana", "cherry"]
x, y, z = fruits
print(x)
print(y)
print(z)

x = "Python is "
y = "awesome"
z =  x + y
print(z)

Global Variables

Variables that are created outside of a function (as in all of the examples above) are
known as global variables.

Global variables can be used by everyone, both inside of functions and outside.

To create a global variable inside a function, you can use the global keyword.

def myfunc():
  global x
  x = "fantastic"

myfunc()

print("Python is " + x)

Python has the following data types built-in by default, in these categories:

Text Type: str

Numeric Types: int, float, complex

Sequence Types: list, tuple, range


Mapping Type: dict

Set Types: set, frozenset

Boolean Type: bool

Binary Types: bytes, bytearray, memoryview

x = 5
print(type(x))

Float can also be scientific numbers with an "e" to indicate the power of 10.

x = 35e3

x = 1    # int

c = complex(x)

print(c)

import random

print(random.randrange(1, 10))

Since strings are arrays, we can loop through the characters in a string, with
a for loop.

for x in "banana":
  print(x)

To check if a certain phrase or character is present in a string, we can use


the keyword in.

Example
Check if "free" is present in the following text:

txt = "The best things in life are free!"


print("free" in txt)

To check if a certain phrase or character is NOT present in a string, we can


use the keyword not in.
Example
Check if "expensive" is NOT present in the following text:
txt = "The best things in life are free!"
print("expensive" not in txt)

You can return a range of characters by using the slice syntax.

Specify the start index and the end index, separated by a colon, to return a
part of the string.

Upper Case
a = "Hello, World!"
print(a.upper())
a = "Hello, World!"
print(a.lower())

Replace String
Example
The replace() method replaces a string with another string:

a = "Hello, World!"
print(a.replace("H", "J"))

Split String
The split() method returns a list where the text between the specified
separator becomes the list items.

Example
The split() method splits the string into substrings if it finds instances of the
separator:

a = "Hello, World!"
print(a.split(",")) # returns ['Hello', ' World!']
We can combine strings and numbers by using the format() method!

The format() method takes the passed arguments, formats them, and places


them in the string where the placeholders {} are:

Example
Use the format() method to insert numbers into strings:

age = 36
txt = "My name is John, and I am {}"
print(txt.format(age))

Example
quantity = 3
itemno = 567
price = 49.95
myorder = "I want {} pieces of item {} for {} dollars."
print(myorder.format(quantity, itemno, price))

You can use index numbers {0} to be sure the arguments are placed in the
correct placeholders:

Example
quantity = 3
itemno = 567
price = 49.95
myorder = "I want to pay {2} dollars for {0} pieces of item {1}."
print(myorder.format(quantity, itemno, price))

Any number is True, except 0.

Any list, tuple, set, and dictionary are True, except empty ones.

These return the value False:

bool(False)
bool(None)
bool(0)
bool("")
bool(())
bool([])
bool({})
Example
Check if an object is an integer or not:

x = 200
print(isinstance(x, int))

% Modulus (Gives the remainder) x%y

** Exponentiation (x^y) x ** y

// Floor division (Gives the integer) x // y

Assignment Operators:

&= x &= 3 x=x&3 Try

|= x |= 3 x=x|3 Try

^= x ^= 3 x=x^3 Try

>>= x >>= 3 x = x >> 3 Try

<<= x <<= 3 x = x << 3

&  AND Sets each bit to 1 if both bits are 1


| OR Sets each bit to 1 if one of two bits is 1

 ^ XOR Sets each bit to 1 if only one of two bits is 1

~  NOT Inverts all the bits

!= Not equal x != y

List Items
List items are ordered, changeable, and allow duplicate values.

It is also possible to use the list() constructor when creating a new list.

Example
Using the list() constructor to make a List:

thislist = list(("apple", "banana", "cherry")) # note the double round-


brackets
print(thislist)

There are four collection data types in the Python programming language:

 List is a collection which is ordered and changeable. Allows duplicate


members.
 Tuple is a collection which is ordered and unchangeable. Allows
duplicate members.
 Set is a collection which is unordered, unchangeable*, and unindexed.
No duplicate members.
 Dictionary is a collection which is ordered** and changeable. No
duplicate members.
thislist = ["apple", "banana", "cherry", "orange", "kiwi", "mango"]
thislist[1:3] = ["blackcurrant", "watermelon"]
print(thislist)

If you insert more items than you replace, the new items will be inserted
where you specified, and the remaining items will move accordingly:

Example
Change the second value by replacing it with two new values:

thislist = ["apple", "banana", "cherry"]
thislist[1:2] = ["blackcurrant", "watermelon"]
print(thislist)

If you insert less items than you replace, the new items will be inserted
where you specified, and the remaining items will move accordingly:

Example
Change the second and third value by replacing it with one value:

thislist = ["apple", "banana", "cherry"]
thislist[1:3] = ["watermelon"]
print(thislist)

Insert Items
To insert a new list item, without replacing any of the existing values, we can
use the insert() method.

The insert() method inserts an item at the specified index:

Example
Insert "watermelon" as the third item:

thislist = ["apple", "banana", "cherry"]
thislist.insert(2, "watermelon")
print(thislist)

Append Items
To add an item to the end of the list, use the append() method:
Example
Using the append() method to append an item:

thislist = ["apple", "banana", "cherry"]
thislist.append("orange")
print(thislist)

Extend List
To append elements from another list to the current list, use
the extend() method.

Example
Add the elements of tropical to thislist:

thislist = ["apple", "banana", "cherry"]
tropical = ["mango", "pineapple", "papaya"]
thislist.extend(tropical)
print(thislist)

The extend() method does not have to append lists, you can add any


iterable object (tuples, sets, dictionaries etc.).

Example
Add elements of a tuple to a list:

thislist = ["apple", "banana", "cherry"]
thistuple = ("kiwi", "orange")
thislist.extend(thistuple)
print(thislist)

The remove() method removes the specified item.

Example
Remove "banana":

thislist = ["apple", "banana", "cherry"]
thislist.remove("banana")
print(thislist)
The pop() method removes the specified index.

Example
Remove the second item:

thislist = ["apple", "banana", "cherry"]
thislist.pop(1)
print(thislist)

If you do not specify the index, the pop() method removes the last item.

Example
Remove the last item:

thislist = ["apple", "banana", "cherry"]
thislist.pop()
print(thislist)

The del keyword also removes the specified index:

Example
Remove the first item:

thislist = ["apple", "banana", "cherry"]
del thislist[0]
print(thislist)

The del keyword can also delete the list completely.

Example
Delete the entire list:

thislist = ["apple", "banana", "cherry"]
del thislist
# thislist = ["apple", "banana", "cherry"]
del thislist [:]------The output is an empty list []
The clear() method empties the list.

The list still remains, but it has no content.

Example
Clear the list content:

thislist = ["apple", "banana", "cherry"]
thislist.clear()
print(thislist)

Loop Through a List


You can loop through the list items by using a for loop:

Example
Print all items in the list, one by one:

thislist = ["apple", "banana", "cherry"]
for x in thislist:
  print(x)

You can also loop through the list items by referring to their index number.

Use the range() and len() functions to create a suitable iterable.

Example
Print all items by referring to their index number:

thislist = ["apple", "banana", "cherry"]
for i in range(len(thislist)):
  print(thislist[i])

Example
Print all items, using a while loop to go through all the index numbers

thislist = ["apple", "banana", "cherry"]
i = 0
while i < len(thislist):
  print(thislist[i])
  i = i + 1
Looping Using List Comprehension
List Comprehension offers the shortest syntax for looping through lists:

Example
A short hand for loop that will print all items in a list:

thislist = ["apple", "banana", "cherry"]
[print(x) for x in thislist]

List Comprehension
List comprehension offers a shorter syntax when you want to create a new
list based on the values of an existing list.

Example:

Based on a list of fruits, you want a new list, containing only the fruits with
the letter "a" in the name.

Without list comprehension you will have to write a for statement with a


conditional test inside:

Example
fruits = ["apple", "banana", "cherry", "kiwi", "mango"]
newlist = []

for x in fruits:
  if "a" in x:
    newlist.append(x)

print(newlist)

With list comprehension you can do all that with only one line of code:

Example
fruits = ["apple", "banana", "cherry", "kiwi", "mango"]

newlist = [x for x in fruits if "a" in x]

print(newlist)
newlist = [expression for item in iterable if condition == True]

newlist = [x for x in range(10)]

Example
Accept only numbers lower than 5:

newlist = [x for x in range(10) if x < 5]

Example
Set the values in the new list to upper case:

newlist = [x.upper() for x in fruits]

Set all values in the new list to 'hello':

newlist = ['hello' for x in fruits]

Example
Return "orange" instead of "banana":

newlist = [x if x != "banana" else "orange" for x in fruits]

Customize Sort Function


You can also customize your own function by using the keyword
argument key = function.

The function will return a number that will be used to sort the list (the lowest
number first):

Example
Sort the list based on how close the number is to 50:

def myfunc(n):
  return abs(n - 50)

thislist = [100, 50, 65, 82, 23]
thislist.sort(key = myfunc)
print(thislist)
By default the sort() method is case sensitive, resulting in all capital letters
being sorted before lower case letters:

Example
Case sensitive sorting can give an unexpected result:

thislist = ["banana", "Orange", "Kiwi", "cherry"]
thislist.sort()
print(thislist)

So if you want a case-insensitive sort function, use str.lower as a key


function:

Example
Perform a case-insensitive sort of the list:

thislist = ["banana", "Orange", "Kiwi", "cherry"]
thislist.sort(key = str.lower)
print(thislist)

What if you want to reverse the order of a list, regardless of the alphabet?

The reverse() method reverses the current sorting order of the elements.

Example
Reverse the order of the list items:

thislist = ["banana", "Orange", "Kiwi", "cherry"]
thislist.reverse()
print(thislist)

There are ways to make a copy, one way is to use the built-in List
method copy().

Example
Make a copy of a list with the copy() method:

thislist = ["apple", "banana", "cherry"]
mylist = thislist.copy()
print(mylist)

Another way to make a copy is to use the built-in method list().


Example
Make a copy of a list with the list() method:

thislist = ["apple", "banana", "cherry"]
mylist = list(thislist)
print(mylist)

Join Two Lists


There are several ways to join, or concatenate, two or more lists in Python.

One of the easiest ways are by using the + operator.

Example
Join two list:

list1 = ["a", "b", "c"]
list2 = [1, 2, 3]

list3 = list1 + list2


print(list3)

Example
Append list2 into list1:

list1 = ["a", "b" , "c"]
list2 = [1, 2, 3]

for x in list2:
  list1.append(x)

print(list1)

Example
Use the extend() method to add list2 at the end of list1:

list1 = ["a", "b" , "c"]
list2 = [1, 2, 3]

list1.extend(list2)
print(list1)
List Methods
Python has a set of built-in methods that you can use on lists.

Method Description

append() Adds an element at the end of the list

clear() Removes all the elements from the list

copy() Returns a copy of the list

count() Returns the number of elements with the specified value

extend() Add the elements of a list (or any iterable), to the end of the current list

index() Returns the index of the first element with the specified value

insert() Adds an element at the specified position

pop() Removes the element at the specified position

remove() Removes the item with the specified value

reverse() Reverses the order of the list


sort() Sorts the list

Tuple
Tuples are used to store multiple items in a single variable.

A tuple is a collection which is ordered and unchangeable.

Tuples are written with round brackets.

Tuple items are ordered, unchangeable, and allow duplicate values.

Tuple items are indexed.

Ordered
When we say that tuples are ordered, it means that the items have a defined
order, and that order will not change.

Unchangeable
Tuples are unchangeable, meaning that we cannot change, add or
remove items after the tuple has been created.

Allow Duplicates
Since tuples are indexed, they can have items with the same value.

Example
Print the number of items in the tuple:

thistuple = ("apple", "banana", "cherry")
print(len(thistuple))
Create Tuple With One Item
To create a tuple with only one item, you have to add a comma after the
item, otherwise Python will not recognize it as a tuple.

Example
One item tuple, remember the comma:

thistuple = ("apple",)
print(type(thistuple))

#NOT a tuple
thistuple = ("apple")
print(type(thistuple))

 Set is a collection which is unordered, unchangeable*, and unindexed.


No duplicate members.

*Set items are unchangeable, but you can remove and/or add items


whenever you like.

 Dictionary is a collection which is ordered** and changeable. No


duplicate members.

Example
Print the second item in the tuple:

thistuple = ("apple", "banana", "cherry")
print(thistuple[1])

Example
Check if "apple" is present in the tuple:

thistuple = ("apple", "banana", "cherry")
if "apple" in thistuple:
  print("Yes, 'apple' is in the fruits tuple")

immutable- unchanging over time or unable to be changed.

You can convert the tuple into a list, change the list, and convert the list back
into a tuple.
Example
Convert the tuple into a list to be able to change it:

x = ("apple", "banana", "cherry")
y = list(x)
y[1] = "kiwi"
x = tuple(y)

print(x)

Add tuple to a tuple. You are allowed to add tuples to tuples, so if you
want to add one item, (or many), create a new tuple with the item(s), and
add it to the existing tuple:

Example
Create a new tuple with the value "orange", and add that tuple:

thistuple = ("apple", "banana", "cherry")
y = ("orange",)
thistuple += y

print(thistuple)

Example
The del keyword can delete the tuple completely:

thistuple = ("apple", "banana", "cherry")
del thistuple
print(thistuple) #this will raise an error because the tuple no longer
exists

In Python, we are also allowed to extract the values back into variables. This
is called "unpacking":

Example
Unpacking a tuple:

fruits = ("apple", "banana", "cherry")

(green, yellow, red) = fruits

print(green)
print(yellow)
print(red)

Note: The number of variables must match the number of values in the


tuple, if not, you must use an asterisk to collect the remaining values as a
list.

Using Asterisk*
If the number of variables is less than the number of values, you can add
an * to the variable name and the values will be assigned to the variable as a
list:

Example
Assign the rest of the values as a list called "red":

fruits = ("apple", "banana", "cherry", "strawberry", "raspberry")

(green, yellow, *red) = fruits

print(green)
print(yellow)
print(red)

If the asterisk is added to another variable name than the last, Python will
assign values to the variable until the number of values left matches the
number of variables left.

Example
Add a list of values the "tropic" variable:

fruits = ("apple", "mango", "papaya", "pineapple", "cherry")

(green, *tropic, red) = fruits

print(green)
print(tropic)
print(red)

f you want to multiply the content of a tuple a given number of times, you
can use the * operator:
Example
Multiply the fruits tuple by 2:

fruits = ("apple", "banana", "cherry")
mytuple = fruits * 2

print(mytuple)

Tuple Methods
Python has two built-in methods that you can use on tuples.

Method Description

count() Returns the number of times a specified value occurs in a tuple

index() Searches the tuple for a specified value and returns the position of wh
was found

A set is a collection which is unordered, unchangeable*, and unindexed.

* Note: Set items are unchangeable, but you can remove items and add


new items.

Once a set is created, you cannot change its items, but you can remove
items and add new items.

Duplicates Not Allowed


Sets cannot have two items with the same value.

Example
Duplicate values will be ignored:
thisset = {"apple", "banana", "cherry", "apple"}

print(thisset)

The set() Constructor


It is also possible to use the set() constructor to make a set.

Example
Using the set() constructor to make a set:

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


brackets
print(thisset)

Example
Check if "banana" is present in the set:

thisset = {"apple", "banana", "cherry"}

print("banana" in thisset)

Example
Add an item to a set, using the add() method:

thisset = {"apple", "banana", "cherry"}

thisset.add("orange")

print(thisset)

Add Sets
To add items from another set into the current set, use the update() method.

Example
Add elements from tropical into thisset:

thisset = {"apple", "banana", "cherry"}
tropical = {"pineapple", "mango", "papaya"}

thisset.update(tropical)
print(thisset)

Add Any Iterable


The object in the update() method does not have to be a set, it can be any
iterable object (tuples, lists, dictionaries etc.).

Example
Add elements of a list to at set:

thisset = {"apple", "banana", "cherry"}
mylist = ["kiwi", "orange"]

thisset.update(mylist)

print(thisset)

Example
Remove "banana" by using the remove() method:

thisset = {"apple", "banana", "cherry"}

thisset.remove("banana")

print(thisset)

Note: If the item to remove does not exist, remove() will raise an error.

Example
Remove "banana" by using the discard() method:

thisset = {"apple", "banana", "cherry"}

thisset.discard("banana")

print(thisset)

Note: If the item to remove does not exist, discard() will NOT raise an


error.
You can also use the pop() method to remove an item, but this method will
remove the last item. Remember that sets are unordered, so you will not
know what item that gets removed.

The return value of the pop() method is the removed item.

Example
Remove the last item by using the pop() method:

thisset = {"apple", "banana", "cherry"}

x = thisset.pop()

print(x)

print(thisset)

Note: Sets are unordered, so when using the pop() method, you do not know


which item that gets removed.

Example
The clear() method empties the set:

thisset = {"apple", "banana", "cherry"}

thisset.clear()

print(thisset)

Example
The del keyword will delete the set completely:

thisset = {"apple", "banana", "cherry"}

del thisset

print(thisset)

Join Two Sets


Example
The union() method returns a new set with all items from both sets:
set1 = {"a", "b" , "c"}
set2 = {1, 2, 3}

set3 = set1.union(set2)
print(set3)

Example
The update() method inserts the items in set2 into set1:

set1 = {"a", "b" , "c"}
set2 = {1, 2, 3}

set1.update(set2)
print(set1)

Note: Both union() and update() will exclude any duplicate items.

Keep ONLY the Duplicates


The intersection_update() method will keep only the items that are present in
both sets.

Example
Keep the items that exist in both set x, and set y:

x = {"apple", "banana", "cherry"}
y = {"google", "microsoft", "apple"}

x.intersection_update(y)

print(x)

The intersection() method will return a new set, that only contains the


items that are present in both sets.

Example
Return a set that contains the items that exist in both set x, and set y:

x = {"apple", "banana", "cherry"}
y = {"google", "microsoft", "apple"}

z = x.intersection(y)

print(z)
The symmetric difference is the union without the intersection: In
mathematics, the symmetric difference of two sets, also known as the
disjunctive union, is the set of elements which are in either of the sets, but
not in their intersection.

Keep All, But NOT the Duplicates


The symmetric_difference_update() method will keep only the elements that are
NOT present in both sets.

Example
Keep the items that are not present in both sets:

x = {"apple", "banana", "cherry"}
y = {"google", "microsoft", "apple"}

x.symmetric_difference_update(y)

print(x)

The symmetric_difference() method will return a new set, that contains


only the elements that are NOT present in both sets.

Example
Return a set that contains all items from both sets, except items that are
present in both:

x = {"apple", "banana", "cherry"}
y = {"google", "microsoft", "apple"}

z = x.symmetric_difference(y)
print(z)

Set Methods
Python has a set of built-in methods that you can use on sets.

Method Description

add() Adds an element to the set

clear() Removes all the elements from the set

copy() Returns a copy of the set

difference() Returns a set containing the difference between two or


sets

difference_update() Removes the items in this set that are also included in
another, specified set

discard() Remove the specified item

intersection() Returns a set, that is the intersection of two other sets

intersection_update() Removes the items in this set that are not present in o
specified set(s)
isdisjoint() Returns whether two sets have a intersection or not

issubset() Returns whether another set contains this set or not

issuperset() Returns whether this set contains another set or not

pop() Removes an element from the set

remove() Removes the specified element

symmetric_difference() Returns a set with the symmetric differences of two se

symmetric_difference_update() inserts the symmetric differences from this set and ano

union() Return a set containing the union of sets

update() Update the set with the union of this set and others

Dictionary
Dictionaries are used to store data values in key:value pairs.

A dictionary is a collection which is ordered*, changeable and do not allow


duplicates.
Dictionary items are presented in key:value pairs, and can be referred to by
using the key name.

Example
Print the "brand" value of the dictionary:

thisdict = {
  "brand": "Ford",
  "model": "Mustang",
  "year": 1964
}
print(thisdict["brand"])

Dictionaries cannot have two items with the same key:

Example
Duplicate values will overwrite existing values:

thisdict = {
  "brand": "Ford",
  "model": "Mustang",
  "year": 1964,
  "year": 2020
}
print(thisdict)

Example
Get the value of the "model" key:

x = thisdict.get("model")

Get Keys
The keys() method will return a list of all the keys in the dictionary.

Example
Get a list of the keys:

x = thisdict.keys()
Example
Add a new item to the original dictionary, and see that the keys list gets
updated as well:

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

x = car.keys()

print(x) #before the change

car["color"] = "white"

print(x) #after the change

Get Values
The values() method will return a list of all the values in the dictionary.

Example
Get a list of the values:

x = thisdict.values()

Example
Make a change in the original dictionary, and see that the values list gets
updated as well:

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

x = car.values()

print(x) #before the change

car["year"] = 2020
print(x) #after the change
Get Items
The items() method will return each item in a dictionary, as tuples in a list.

Example
Get a list of the key:value pairs

x = thisdict.items()

Check if Key Exists


To determine if a specified key is present in a dictionary use the in keyword:

Example
Check if "model" is present in the dictionary:

thisdict = {
  "brand": "Ford",
  "model": "Mustang",
  "year": 1964
}
if "model" in thisdict: # (By default it refers to keys only not
values)
  print("Yes, 'model' is one of the keys in the thisdict dictionary")
or
thisdict = {
"brand": "Ford",
"model": "Mustang",
"year": 1964
}
x= "color" in thisdict.keys()

You can change the value of a specific item by referring to its key name:

Example
Change the "year" to 2018:
thisdict = {
  "brand": "Ford",
  "model": "Mustang",
  "year": 1964
}
thisdict["year"] = 2018

The update() method will update the dictionary with the items from the
given argument.

The argument must be a dictionary, or an iterable object with key:value


pairs.

Example
Update the "year" of the car by using the update() method:

thisdict = {
  "brand": "Ford",
  "model": "Mustang",
  "year": 1964
}
thisdict.update({"year": 2020})
thisdict.update({"year": 2020,"model":"Fiesta",})
thisdict = {
"brand": "Ford",
"model": "Mustang",
"year": 1964
}
thisdict.update({"built": "iron","place":"Florida"})

print(thisdict)

Removing Items
There are several methods to remove items from a dictionary:

Example
The pop() method removes the item with the specified key name:
thisdict = {
  "brand": "Ford",
  "model": "Mustang",
  "year": 1964
}
thisdict.pop("model")
print(thisdict)

Example
The popitem() method removes the last inserted item 

thisdict = {
  "brand": "Ford",
  "model": "Mustang",
  "year": 1964
}
thisdict.popitem()
print(thisdict)

Example
The del keyword removes the item with the specified key name:

thisdict = {
  "brand": "Ford",
  "model": "Mustang",
  "year": 1964
}
del thisdict["model"]
print(thisdict)

Example
The del keyword can also delete the dictionary completely:

thisdict = {
  "brand": "Ford",
  "model": "Mustang",
  "year": 1964
}
del thisdict
print(thisdict) #this will cause an error because "thisdict" no longer
exists.

Example
The clear() method empties the dictionary:
thisdict = {
  "brand": "Ford",
  "model": "Mustang",
  "year": 1964
}
thisdict.clear()
print(thisdict)

Example
Print all key names in the dictionary, one by one:

for x in thisdict:
  print(x)

Example
You can also use the values() method to return values of a dictionary:

for x in thisdict.values():
  print(x)

Print all key names in the dictionary, one by one:

for x in thisdict:
  print(x)

Example
Print all values in the dictionary, one by one:

for x in thisdict:
  print(thisdict[x])

Example
You can also use the values() method to return values of a dictionary:

for x in thisdict.values():
  print(x)

Example
You can use the keys() method to return the keys of a dictionary:

for x in thisdict.keys():
  print(x)
Example
Loop through both keys and values, by using the items() method:

for x, y in thisdict.items():
  print(x, y)

Example
Make a copy of a dictionary with the copy() method:

thisdict = {
  "brand": "Ford",
  "model": "Mustang",
  "year": 1964
}
mydict = thisdict.copy()
print(mydict)

Example
Make a copy of a dictionary with the dict() function:

thisdict = {
  "brand": "Ford",
  "model": "Mustang",
  "year": 1964
}
mydict = dict(thisdict)
print(mydict)

Nested Dictionaries
A dictionary can contain dictionaries, this is called nested dictionaries.

Example
Create a dictionary that contain three dictionaries:

myfamily = {
  "child1" : {
    "name" : "Emil",
    "year" : 2004
  },
  "child2" : {
    "name" : "Tobias",
    "year" : 2007
  },
  "child3" : {
    "name" : "Linus",
    "year" : 2011
  }
}

Example
Create three dictionaries, then create one dictionary that will contain the
other three dictionaries:

child1 = {
  "name" : "Emil",
  "year" : 2004
}
child2 = {
  "name" : "Tobias",
  "year" : 2007
}
child3 = {
  "name" : "Linus",
  "year" : 2011
}

myfamily = {
  "child1" : child1,
  "child2" : child2,
  "child3" : child3
}

Short Hand If
If you have only one statement to execute, you can put it on the same line
as the if statement.

Example
One line if statement:

if a > b: print("a is greater than b")

Short Hand If ... Else


If you have only one statement to execute, one for if, and one for else, you
can put it all on the same line:

Example
One line if else statement:

a = 2
b = 330
print("A") if a > b else print("B")

You can also have multiple else statements on the same line:

Example
One line if else statement, with 3 conditions:

a = 330
b = 330
print("A") if a > b else print("=") if a == b else print("B")

The pass Statement


if statements cannot be empty, but if you for some reason have
an if statement with no content, put in the pass statement to avoid getting
an error.

Example
a = 33
b = 200

if b > a:
  pass

You might also like