Python Lists, Sets, Tuples, Dictionaries
Python Lists, Sets, Tuples, Dictionaries
• Alistcanbedefinedasacollectionofvaluesoritemsofsameordifferenttypes.
• Theitemsinthelistareseparatedwiththecomma(,)andenclosedwiththe squarebrackets[].
• Alistisavaluethatcontainsmultiple valuesinanorderedsequence.
• Alistismutable(new,deleted,modify).
• Thevaluesinlistare calledelementsorsometimesitems.
Creating a List
Alistcanbedefinedasfollows.
Alistcanbedisplayedasfollows.
print(L1) #displays['Raju',102,'India']
Listindexingandsplitting
>>>spam #['cat','bat','rat','elephant']
>>>spam[0] #'cat'
>>>spam[1] #'bat'
>>>spam[2] #'rat'
>>>spam[3] #'elephant‘
>>>spam[int(1.0)] #’bat’
>>>spam[4] #IndexError:listindexoutofrange
>>>'Hello'+spam[2] #'Hellorat‘
>>>spam #[['cat','bat'],[10,20,30,40,50]]
>>>spam[0][1] #'bat'
>>>spam[1][4] #50
>>>spam[1][5] #IndexError
Negative Indexes
• Indexesstartat0andgoup,wecanalsousenegativeintegersfortheindex.
• Theintegervalue-1referstothelastindexinalist,thevalue -2referstothesecond-to-last indexin a list, and
so on.
>>>spam=['cat','bat','rat','elephant']
>>>spam[-1] #'elephant'
>>>spam[-3] #'bat'
>>>spam[3] #elephant
>>>spam[-1] #'elephant'
>>>spam[-3] #'bat'
#'Theelephant isafraidofthebat.'
• Thedifferencebetweenindexesandslices.
o spam[2]isalistwithanindex(oneinteger).
o spam[1:4]isalistwithaslice(twointegers).
>>>spam=['cat','bat','rat','elephant']
>>>spam[0:4] #['cat','bat','rat','elephant']
>>>spam[1:3] #['bat','rat']
>>>spam[::-1] #['elephant','rat','bat','cat']
>>>spam[:2] #['cat','bat']printselementsofpos0and1
>>>spam[1:] #['bat','rat','elephant']printsallexcluding0
>>>spam[:] #['cat','bat','rat','elephant']printsall
GettingaList’sLengthwith len()
>>>len(spam)
ChangingValuesin aList withIndexes
>>>spam[1]='aardvark‘ #pos1batvalueischangedtoaardvark
>>>spam #['cat','aardvark','rat','elephant']
>>>spam #['cat','aardvark','aardvark','elephant']
>>>spam[-1]=12345 #lastposvaueischangedto12345
>>>spam #['cat','aardvark','aardvark',12345]
>>>spam = [1, 2, 3]
>>>spam=spam+['A', 'B','C']
>>>spam #[1,2,3,'A','B','C']
Thedelstatement willdeletevaluesatanindexinalist.
>>>spam=['cat','bat','rat','elephant']
>>>delspam[2] #deleteselementatpos2
>>>spam #['cat','bat','elephant']
>>>delspam[2] #deleteselementatpos2
lastelement
10 usingnegativeindexing.
>>>print(a[0:3])
[2,3,4] Printingapartofthelist.
Slicing
>>>print(a[0:])
[2,3,4,5, 6, 7,8,9, 10]
>>>b=[20,30] Addingandprintingthe
Concatenation >>>print(a+b) items of two lists.
>>>print(a[2]) Updatingthelistusing
4 indexvalue.
Updating >>> a[2]=100
>>>print(a)
[2,3,100, 5, 6, 7,8,9, 10]
Membership a=[2,3,4,5,6,7,8,9,10] ReturnsTrueifelementispr
>>>5 ina [Link]
True nsfalse.
>>>100ina
False
>>>2notina
False
a=[2,3,4,5,6,7,8,9,10] ReturnsTrueifallelementsi
Comparison
>>>b=[2,3,4] nbothelementsaresame.
>>>a==b Otherwisereturnsfalse
False
>>>a!=b
True
Syntax:[Link](element/index/list)
>>>a=[7,6,5,4, 3,2, 1]
[Link](element) >>>[Link](1) Removesanitem
>>>print(a) fromthelist
[7,6, 5,4,3, 2]
[Link](element) >>>a=[7,6, 5,4, 3, 2,6] Returnsthecountof
>>>[Link](6) numberofitems
2 passedasan
argument
List loops:
1. Forloop
2. Whileloop
3. Infiniteloop
Syntax:
forvalinsequence:
Accessingelement output
a=[10,20,30,40,50] 10
foriin a: 20
print(i) 30
40
50
Accessingindex output
a=[10,20,30,40,50] 0
fori in range(0,len(a),1): 1
print(i) 2
3
4
Accessingelementusingrange: output
a=[10,20,30,40,50] 10
foriin range(0,len(a),1): 20
print(a[i]) 30
40
50
The while loop in Python is used to iterate over a block of code as long as the test expression
(condition) is [Link] the condition is tested and the result is false, the loop body will be
skipped and the first statement after the while loop will be executed.
Syntax:
while (condition): body of while
Sum of elements in list Output:15
a=[1,2,3,4,5]
i=0 sum=0
while i<len(a): sum=sum+a[i] i=i+1
print(sum)
Mutability:
Lists are mutable. (can be changed)
Mutability is the ability for certain types of data to be changed without entirely
recreating it.
An item can be changed in a list by accessing it directly as part of the assignment
statement.
Using the indexing operator (square brackets[ ]) on the left side of an assignment, one of
the list items can be updated.
Example description
Aliasing:
Creating a copy of a list is called aliasing.
When you create a copy both the list will be having same memory location.
changes in one list will affect another list.
Alaising refers to having different names for same list values.
Example Output:
a= [1, 2, 3 ,4 ,5]
b=a
print (b) [1, 2, 3, 4, 5]
a is b True
a[0]=100
print(a) [100,2,3,4,5]
print(b) [100,2,3,4,5]
Clonning:
To avoid the disadvantages of copying we are using cloning.
Creating a copy of a same list of elements with two different memory locations is called
cloning.
Changes in one list will not affect locations of aother list.
Cloning is a process of making a copy of the list without modifying the original
list.
Slicing
list()method
copy() method
clonning using Slicing
>>>a=[1,2,3,4,5]
>>>b=a[:]
>>>print(b) [1,2,3,4,5]
>>>a is b
False #because they have different memory location
clonning using List( ) method
>>>a=[1,2,3,4,5]
>>>b=list
>>>print(b) [1,2,3,4,5]
>>>a is b false
>>>a[0]=100
>>>print(a)
>>>a=[100,2,3,4,5]
>>>print(b)
>>>b=[1,2,3,4,5]
clonning using copy() method
a=[1,2,3,4,5]
>>>b=[Link]()
>>> print(b) [1, 2, 3, 4, 5]
>>> a is b False
Tuple:
A tuple is same as list, except that the set of elements is enclosed in parentheses
instead of square brackets.
A tuple is an immutable list. i.e. once a tuple has been created, you can't add
elements to a tuple or remove elements from the tuple.
But tuple can be converted into list and list can be converted in to tuple.
Creating a Tuple
Creating the tuple with
>>>a=(20,40,60,”apple”,”ball”) elementsofdifferent data
types.
Indexing:
>>>print(a[0]) 20 Accessingtheiteminthe position 0
>>>a[2] Accessingtheiteminthe
60 position2
Deleting a Tuple:
del(tuple) >>>del(a) Deletetheentiretuple.
Tuple operations:
Indexing
Slicing
Concatenation
Repetitions
Membership
Comparison
Operations examples description
Creating the tuple with
Creating a tuple >>>a=(20,40,60,”apple”,”ball”) elements of different data
types.
>>>print(a[0]) Accessing the item in the
Indexing 20 position 0
>>> a[2] Accessing the item in the
60 position 2
Slicing >>>print(a[1:3]) Displaying items from 1st
(40,60) till 2nd.
Concatenation >>> b=(2,4) Adding tuple elements at
>>>print(a+b) the end of another tuple
>>>(20,40,60,”apple”,”ball”,2,4) elements
Repetition >>>print(b*2) repeating the tuple in n no
>>>(2,4,2,4) of times
>>> a=(2,3,4,5,6,7,8,9,10)
>>> 5 in a
Membership True Returns True if element is
>>> 100 in a present in tuple. Otherwise
False returns false.
>>> 2 not in a
False
>>> a=(2,3,4,5,6,7,8,9,10)
>>>b=(2,3,4) Returns True if all elements
Comparison
>>> a==b in both elements are same.
False Otherwise returns false
>>> a!=b
True
Tuple methods:
Tuple Assignment:
Tuple assignment allows, variables on the left of an assignment operator and
values of tuple on the right of the assignment operator.
Multiple assignment works by creating a tuple of expressions from the right
hand side, and a tuple of targets from the left, and then matching each
expression to a target.
Because multiple assignments use tuples to work, it is often termed tuple
assignment.
Uses of Tuple assignment:
It is often useful to swap the values of two variables.
Swapping using temporary variable: Swapping using tuple assignment:
a=20 a=20
b=50 b=50
temp = a (a,b)=(b,a)
a=b print("value after swapping is",a,b)
b = temp
print("value after swapping is",a,b)
Multipleassignments:
Multiplevaluescanbeassignedtomultiplevariablesusingtuple assignment.
>>>(a,b,c)=(1,2,3)
>>>print(a)
1
>>>print(b)
2
>>>print(c)
3
Tuple as return value:
A Tuple is a comma separated sequence of items.
It is created with or without ( ).
A function can return one value. if you want to return more than one value from a
function. we can use tuple as return value.
Example1: Output:
def div(a,b): enter a value:4
r=a%b enter b value:3
q=a//b reminder: 1
return(r,q) quotient: 1
a=eval(input("enter a value:"))
b=eval(input("enter b value:"))
r,q=div(a,b)
print("reminder:",r)
print("quotient:",q)
Example2: Output:
def min_max(a): smallest: 1
small=min(a) biggest: 6
big=max(a)
return(small,big)
a=[1,2,3,4,6]
small,big=min_max(a)
print("smallest:",small)
print("biggest:",big)
Tupleasargument:
Theparameternamethatbeginswith *gathersargumentintoatuple.
Example: Output:
def printall(*args): (2, 3, 'a')
print(ar
gs)
printall(2,
3,'a')
Set: Creating a set, Python Set Operations, Python Built-in set methods.
Dictionary: Creating the dictionary, Properties of Keys and Values, Accessing the
dictionary values, and adding dictionary values, Iterating Dictionary, Built in Dictionary
functions.
Set Introduction
Sets in Python are an unordered collection of unique, immutable elements. They are
mutable themselves, meaning elements can be added or removed after creation, but the
individual elements within a set must be immutable (e.g., numbers, strings, tuples). Sets
are particularly useful for operations that involve uniqueness, membership testing, and
mathematical set operations.
Unordered:
Elements in a set do not maintain a specific order and cannot be accessed by index.
Unique Elements:
Sets automatically handle duplicate values; if you try to add an existing element, it will
not be added again.
Mutable:
You can add or remove elements from a set after it's created.
Immutable Elements:
While the set itself is mutable, the individual elements stored within it must be of an
immutable data type.
Creating a set
Sets can be created using curly braces {} or the set() constructor.
# Using curly braces
my_set = {1, 2, 3, 4, 5}
print(my_set)
# Using the set() constructor with an iterable (e.g., a list)
another_set = set([1, 2, 2, 3, 4])
print(another_set) # Output will be {1, 2, 3, 4} due to uniqueness
Adding Elements:
add(element): Adds a single element to the set.
Removing Elements:
remove(element): Removes a specified element. Raises a KeyError if the element is
not found.
Set Mathematics:
union() or |: Returns a new set containing all unique elements from both sets.
intersection() or &: Returns a new set containing common elements from both sets.
difference() or -: Returns a new set containing elements present in the first set but not
in the second.
Membership Testing:
in keyword: Checks if an element is present in the set.
set_a = {1, 2, 3}
set_b = {3, 4, 5}
# Add an element
set_a.add(6)
print(f"Set A after adding 6: {set_a}")
# Union
union_set = set_a.union(set_b)
print(f"Union of A and B: {union_set}")
# Intersection
intersection_set = set_a.intersection(set_b)
print(f"Intersection of A and B: {intersection_set}")
# Membership test
print(f"Is 2 in set_a? {2 in set_a}")
Python's built-in set type provides various methods for manipulating and performing
operations on sets. These methods can be broadly categorized as follows:
1. Adding Elements:
add(element): Adds a single element to the set. If the element is already present, the
set remains unchanged.
update(iterable): Adds all elements from an iterable (like another set, list, or tuple) to
the set. Duplicate elements are ignored.
2. Removing Elements:
remove(element): Removes the specified element from the set. Raises a KeyError if
the element is not found.
discard(element): Removes the specified element from the set. Does nothing if the
element is not found (no error is raised).
pop(): Removes and returns an arbitrary element from the set. Raises a KeyError if the
set is empty.
3. Set Operations:
union(other_set) or set1 | set2: Returns a new set containing all unique elements from
both sets.
intersection(other_set) or set1 & set2: Returns a new set containing only the
common elements between the sets.
issubset(other_set) or set1 <= set2: Returns True if all elements of the first set are
present in the second set.
issuperset(other_set) or set1 >= set2: Returns True if all elements of the second set
are present in the first set.
intersection_update(other_set) or set1 &= set2: Updates the set to contain only the
common elements with another set.
Dictionary Introduction
A Python dictionary is a built-in data structure that stores data in key-value pairs. It is a
collection that is ordered (as of Python 3.7+), changeable, and does not allow duplicate
keys.
Key Characteristics:
Key-Value Pairs:
Changeable (Mutable):
No Duplicate Keys:
Each key within a dictionary must be unique. If a duplicate key is assigned, it will
overwrite the previous value associated with that key.
Properties of Keys:
Immutability:
Dictionary keys must be immutable objects. This means they cannot be changed after
creation. Examples of immutable types suitable for keys include strings, numbers
(integers, floats), and tuples. Mutable types like lists or other dictionaries cannot be
used as keys.
Uniqueness:
Each key within a single dictionary must be unique. Duplicate keys are not allowed; if a
key is assigned a new value, the previous value associated with that key will be
overwritten.
Hashability:
Keys must be hashable, meaning they must have a hash value that can be used for
efficient lookup. Immutable types are generally hashable.
Case Sensitivity:
Keys are case-sensitive. For example, 'Key' and 'key' are treated as distinct keys.
Properties of Values:
Mutability:
Dictionary values can be of any data type, including mutable types like lists, other
dictionaries, or custom objects. They can be changed or updated after the dictionary is
created.
Duplication Allowed:
Unlike keys, values in a dictionary can be duplicated. Multiple keys can point to the
same value.
No Hashability Requirement:
Accessibility:
Values are accessed using their corresponding keys. You cannot directly access a key
using its value.
Values are accessed using their corresponding keys, either by enclosing the key in
square brackets [] or by using the get() method.
# Accessing values
print(my_dict["name"]) # Output: Alice
print(my_dict.get("age")) # Output: 30
Iterating Dictionary
In Python, dictionaries can be iterated in several ways to access their keys, values, or
both.
When a dictionary is directly used in a for loop, it iterates over its keys.
The values() method returns a view object that displays a list of all the values in the
dictionary.
The keys() method returns a view object that displays a list of all the keys in the
dictionary. While directly iterating over the dictionary also yields keys, keys() is
explicit.
Python provides several built-in functions that can be used with dictionaries, as well as
a set of methods specific to dictionary objects.
len(dictionary): Returns the number of key-value pairs (items) in the dictionary.
dict(): This is the dictionary constructor. It can be used to create an empty dictionary or
to create a dictionary from an iterable of key-value pairs (e.g., a list of tuples).
empty_dict = dict()
print(empty_dict)
sorted(dictionary): Returns a new sorted list of the dictionary's keys. The sorting
order is determined by the default comparison for the key types.
all(dictionary): Returns True if all keys in the dictionary are truthy (evaluate to True),
or if the dictionary is empty. Returns False otherwise.
any(dictionary): Returns True if any key in the dictionary is truthy, or if the dictionary
is empty. Returns False if all keys are falsy.
Note: While these built-in functions can interact with dictionaries, dictionaries also have
a rich set of methods (e.g., keys(), values(), items(), get(), pop(), update(), etc.) that are
specifically designed for dictionary manipulation and retrieval.
Sample Questions
1. Difference between List and Dictionary in Python with example program for each.
2. Difference between List and Tuple in Python with example program for each.
3. Convert list of tuple into dictionary using iterative method with example program.
4. Which is better list or tuple in Python? Justify your answer with example program?
7. Give any two ways to create a list in Python and reverse a list.
8. Explain the different list methods in Python for Python lists and give example
program for any five.
10. Explain the append() and extend() in Python with suitable program for each.
11. Given a list of lists, write a Python program to extract the last element of each
sublist in the given list of lists.
12. List out the Different Operations Related to Tuples. Explain any five with example
program for each.
13. Explain the different tuple methods in Python for Python tuples and give example
program for each.
15. List out the Different Operations Related to sets. Explain with example program.
16. Explain the different set methods in Python for Python tuples and give example
program for each.
17. Create a dictionary and explain the properties of keys and values.
18. Explain any 5 ways to iterate through a dictionary with suitable example for each.
19. Write a python program to removing dictionary from list of dictionaries with
output.
20. What are the built-in methods that you can use on dictionaries? Explain any five
with an example program.