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

Module Lists Dic Tuples

The document discusses various Python data types including lists, dictionaries, tuples and sets. It provides details on how to create, access and modify items in lists and dictionaries. It also describes various methods that can be used on lists and built-in functions used on dictionaries.

Uploaded by

Prachi Sharma
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
10 views

Module Lists Dic Tuples

The document discusses various Python data types including lists, dictionaries, tuples and sets. It provides details on how to create, access and modify items in lists and dictionaries. It also describes various methods that can be used on lists and built-in functions used on dictionaries.

Uploaded by

Prachi Sharma
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 50

MODULE 3: LISTS,

DICTONARIES,
TUPLES & SETS
>>> Overview

LEARNING OUTCOMES

 Create and manipulate items in lists.


 Comprehend Indexing and slicing in lists.
 Use methods associated with lists.
 Create and manipulate key:value pairs in dictionaries.
 Create and manipulate items in tuples.
 Use for loop to access individual items in tuples.
 Understand the relation between dictionaries and tuples.
 Understand the relation between lists and tuples.
Lists in Python
Python has a data type known as a list. For our purposes, lists are arrays.

Declaration syntax: <name> = [<value>, <value>, <value>, …, <value>]


<name> = [<default value>] * <initial array size>

Example: numbers = [12, 49, -2, 26, 5, 17, -6]


zeros = [0] * 10

Indexing: Lists have zero based indexing from front


Negative Indexing: You can also refer to an element by a negative index representing how far it
is from the end.

Example: index from front 0 1 2 3 4 5


numbers = [ 13, 25, 39, 46, 54, 68]
index from back -6 -5 -4 -3 -2 -1
Methods for Lists
Basic Methods – directly modify the lists
• list.append(item) – appends the item to the end of the list
• list.insert(index, item) – inserts the item at the specified index
• list.remove(item) – removes the first occurrence of item from the list
•list.extend(second_list) – appends second_list to the list

Mathematical Operators – behave as you would expect them to


• (+) Returns a new list by adding two lists. Appends the right-hand list to the left-hand list.
• (+=) Appends the right-hand list to the left-hand list. Modifies left list. Acts like extend()
• (*) Multiplies a list and an integer “n”. Returns a new list that has n-1 versions of
original list appended to it
Examples:
list = [34, 21, 29, 86, 29] list2 = [1, 2, 3, 4]

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

Slicing – can get a sub list of a list


<name>[<first index inclusive> : <second index not-inclusive>]

list = [4, 23, 16, 7, 29, 56, 81]


list[3:6] => [16, 7, 29]

Length of lists
len(list) => 7

Split – returns a list


“lets try some splitting here”.split(“ “) => ['lets', 'try', 'some', 'splitting', 'here']
Printing Lists
There are two ways to print lists.

list1 = *“elements”, “of”, “our”, “list”+


list2 = [21, 29, 86, 19, 42]

String concatenation and type conversion:

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]

Comma separated arguments in the print method:


print “This list is”, list1 => This list is *“elements”, “of”, “our”, “list”+
print “This list is”, list2 => This list is [21, 29, 86, 19, 42]
Ranges are Lists

Recall how we used the method range() in for loops.


Calling range returns a list with the patterns specified by
range().

Example:
range(5) => [0, 1, 2, 3, 4]
range(0, 10, 2) => [0, 2, 4, 6, 8]

Using a for loop iterates over each element in a list.

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

total_items = int(input("Enter the number of items "))


for i in range(total_items):
item = input("Enter list item: ")
items_of_list.append(item)
print(f"List items are {items_of_list}")
Traversing of Lists

Using a for loop you can iterate through each item in a list.

fast_food = ["waffles", "sandwich", "burger", "fries"]


for each_food_item in fast_food:
print(f"I like to eat {each_food_item}")
for each_food_item in ["waffles", "sandwich", "burger", "fries"]:
print(f"I like to eat {each_food_item}")
Program to Display the Index Values of Items in List

Using a for loop you can iterate through each item in a list.

silicon_valley = ["google", "amd", "yahoo", "cisco", "oracle"]


for index_value in range(len(silicon_valley)):
print(f"The index value of ',silicon_valley*index_value+-’ is {index_value}")

To convert the sentence to list of words in a sentence:


str="hello python is a great language"
lstofwords=str.split()
print(lstofwords)

output: ['hello', 'python', 'is', 'a', 'great', 'language']


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

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

Another useful data type built into Python is the Dictionary.

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’-

A value in the dictionary can


be of any data type including
string, number, list, or dictionary
itself.
Dictionaries

In dictionaries, the order of key:value pairs does not matter. For example,

>>> pizza = {"pepperoni":3, "calzone":5, "margherita":4}


>>> fav_pizza = {"margherita":4, "pepperoni":3, "calzone":5}
>>> pizza == fav_pizza
True

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

 Each individual key:value pair in a dictionary can be accessed through


keys by specifying it inside square brackets.
 The syntax for accessing the value for a key in the dictionary is,
dictionary_name[key]

 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

The built-in dict() function is used to create dictionary.


dict([**kwarg])
Example:
>>> numbers = dict(one=1, two=2, three=3)
>>> numbers
{'one': 1, 'two': 2, 'three': 3}

Keyword arguments of the form kwarg = value are converted to key:value


pairs for numbers dictionary.
Built-In Functions Used on Dictionaries

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

 Dictionary allows you to store data in key:value format without


depending on indexing.
keys = {'a', 'e', 'i', 'o', 'u' }

vowels = dict.fromkeys(keys)
print(vowels)
{'a': None, 'u': None, 'o': None, 'e': None, 'i': None}

keys = {'a', 'e', 'i', 'o', 'u' }


value = 'vowel'

vowels = dict.fromkeys(keys, value)


print(vowels)

Output

{'a': 'vowel', 'u': 'vowel', 'o': 'vowel', 'e': 'vowel', 'i': 'vo
original_marks = {'Physics':67, 'Maths':87}

copied_marks = original_marks.copy()

print('Original Marks:', original_marks)


print('Copied Marks:', copied_marks)

# Output: Original Marks: {'Physics': 67, 'Maths': 87}


# Copied Marks: {'Physics': 67, 'Maths': 87

person = {'name': 'Phill', 'age': 22}

print('Name: ', person.get('name'))


print('Age: ', person.get('age'))

# value is not provided


print('Salary: ', person.get('salary'))
person = {'name': 'Phill', 'age': 22, 'salary': 3500.0}
print(person.keys())
output: dict_keys(['name', 'salary', 'age'])
sales = { 'apple': 2, 'orange': 3, 'grapes': 4 }

element = sales.pop('apple')

print('The popped element is:', element)


print('The dictionary is:', sales)
output: The popped element is: 2
The dictionary is: {'orange': 3, 'grapes': 4}
sales = { 'apple': 2, 'orange': 3, 'grapes': 4 }

element = sales.pop('guava', 'nil')

print('The popped element is:', element)


print('The dictionary is:', sales)

the popped element is: nil


The dictionary is: {'orange': 3, 'apple': 2, 'grapes': 4}

person = {'name': 'Phill', 'age': 22, 'salary': 3500.0}


result = person.popitem()
print('Return Value = ', result)
print('person = ', person)

output: Return Value = ('salary', 3500.0)


person = {'name': 'Phill', 'age': 22}
person = {'name': 'Phill'}

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

 One of the common ways of populating dictionaries is to start with an


empty dictionary { }, then use the update() method to assign a value to the
key using assignment operator.
 For example,

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

currency = {"India": "Rupee", "USA": "Dolla r", "Russia": "Ruble",


"Japan": "Yen", "Germany": "Euro"}
def main():
print("List of Countries")
for key in currency.keys():
print(key)
print("List of Currencies in different Countries")
for value in currency.values():
print(value)
for key, value in currency.items():
print(f"'{key}' has a currency of type '{value}'")
if name == " main ":
main()
The del Statement

 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.

animals = {"r":"rat", "c":"cat", "m":"monkey"}


animals
{'r': 'rat', 'c': 'cat', 'm': 'monkey'}
del animals["c"]
animals
{'r': 'rat', 'm': 'monkey'}
empty dictionary
my_dict = {}

# dictionary with integer keys


my_dict = {1: 'apple', 2: 'ball'}
# dictionary with mixed keys
my_dict = {'name': 'John', 1: [2, 4, 3]}
# using dict()
my_dict = dict({1:'apple', 2:'ball'})

# from sequence having each item as a pair


my_dict = dict([(1,'apple'), (2,'ball')])
Tuples and Sets
 Tuple is one of 4 built-in data types in Python used to store collections of
data, the other 3 are List, Set, and Dictionary, all with different qualities
and usage.
 A tuple is a finite ordered list of values of possibly different types which is
used to bundle related values together without having to create a specific
type to hold them.
 Tuples are immutable. Once a tuple is created, you cannot change its
values.
 The syntax for creating tuples is,
Tuples and Sets
For example,
>>> internet = ("cern", "timbernerslee", "www", 1980)
>>> internet
('cern', 'timbernerslee,' 'www', 1980)
>>> type(internet)
<class 'tuple’>

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.

>>> air_force = ("f15", "f22a", "f35a")


>>> fighter_jets = (1988, 2005, 2016, air_force)
>>> fighter_jets
(1988, 2005, 2016, ('f15', 'f22a', 'f35a'))
>>> type(fighter_jets)
<class 'tuple'>
Basic Tuple Operations
Like in lists, you can use the + operator to concatenate tuples together and the
* operator to repeat a sequence of tuple items.
For example,

>>> tuple_1 = (2, 0, 1, 4)


>>> tuple_2 = (2, 0, 1, 9)
>>> tuple_1 + tuple_2
(2, 0, 1, 4, 2, 0, 1, 9)
>>> tuple_1 * 3
(2, 0, 1, 4, 2, 0, 1, 4, 2, 0, 1, 4)
>>> tuple_1 == tuple_2
False
Indexing and Slicing in Tuples
 Each item in a tuple can be called individually through indexing. The
expression inside the bracket is called the index.
 The syntax for accessing an item in a tuple is,
tuple_name[index]
For example,

>>> holy_places = ("jerusalem", "kashivishwanath", "harmandirsahib",


"bethelhem", "mahabodhi")
>>> holy_places
('jerusalem', 'kashivishwanath', 'harmandirsahib', 'bethlehem', 'mahabodhi')
>>> holy_places[0]
'jerusalem'
>>> holy_places[5]
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
IndexError: tuple index out of range
Indexing and Slicing in Tuples
 Slicing of tuples is allowed in Python wherein a part of the tuple can be
extracted by specifying an index range along with the colon (:) operator,
which itself results as tuple type.
 The syntax for tuple slicing is,

 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:

>>> colors = ("v", "i", "b", "g", "y", "o", "r“


>>> colors[1:4]
('i', ' b', 'g’)
>>> colors[:]
('v', 'i', ' b', 'g', 'y', 'o', 'r')
>>> colors[1:5:2]
('i', 'g')
colors[::-1]
('r', 'o', 'y', 'g', ' b', 'i', 'v')
>>> colors[-5:-2]
(' b', 'g', 'y')
Built-In Functions Used on Tuples
 There are many built-in functions (TABLE) for which a tuple can be passed
as an argument.

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,

>>> coral_reef = ("great_barrier", "ningaloo_coast", "amazon_reef",


"pickles_reef")
>>> coral_reef[0] = "pickles_reef"
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: 'tuple' object does not support item assignment
Difference between Tuples and Lists
Sl.No LIST TUPLE
1 Lists are mutable Tuples are immutable

2 The implication of iterations is


Implication of iterations is Time-consuming
comparatively Faster

3 The list is better for performing operations, such Tuple data type is appropriate for accessing
as insertion and deletion. the elements

4 Tuple consume less memory as compared to


Lists consume more memory
the list

5 Lists have several built-in methods Tuple does not have many built-in methods.

6 The unexpected changes and errors are more


In tuple, it is hard to take place.
likely to occur
Tuple 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.

Program to Iterate Over Items in Sets Using for Loop:

warships = {"u.s.s._arizona", "hms_beagle", "ins_airavat", "ins_hetz"}


def main():
for each_ship in warships:
print(f"{each_ship} is a Warship")
if name == " main ":
main()

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

You might also like