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

Unit 4

Uploaded by

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

Unit 4

Uploaded by

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

Python Lists

Unit- IV
Dr. T. Nikil Prakash
Assistant Professor
Department of Information Technology
St. Joseph’s College (Autonomous)
Tiruchirappalli-02
Lists
• Python Lists are just like dynamically sized arrays, declared in other
languages (vector in C++ and ArrayList in Java).
• In simple language, a list is a collection of things, enclosed in [ ] and
separated by commas.

• The list is a sequence data type which is used to store the collection of
data.
• Tuples and String are other types of sequence data types.
• Example
• Var = ["Geeks", "for", "Geeks"]
• print(Var)

• Output:

• ["Geeks", "for", "Geeks"]


• Lists are the simplest containers that are an integral part of the
Python language.
• Lists need not be homogeneous always which makes it the most
powerful tool in Python.
• A single list may contain DataTypes like Integers, Strings, as
well as Objects.
• Lists are mutable, and hence, they can be altered even after
their creation
• Creating a List in Python
• Lists in Python can be created by just placing the sequence
inside the square brackets[].
• Unlike Sets, a list doesn’t need a built-in function for its creation
of a list.
• Example
• # Creating a List
• List = []
• print("Blank List: ")
• print(List)
Output
• # Creating a List of numbers Blank List:
• List = [10, 20, 14] []
• print("\nList of numbers: ")
• print(List)
List of numbers:
[10, 20, 14]
• # Creating a List of strings and accessing
• # using index
List Items:
• List = ["Geeks", "For", "Geeks"]
Geeks
• print("\nList Items: ")
Geeks
• print(List[0])
• print(List[2])
• Accessing elements from the List
• In order to access the list items refer to the index number.
• Use the index operator [ ] to access an item in a list.
• The index must be an integer. Nested lists are accessed using nested
indexing.
• Example
• # Creating a List with
• # the use of multiple values
• List = ["Geeks", "For", "Geeks"]

• # accessing a element from the


• # list using index number
• print("Accessing a element from the list") Output
Accessing a element from
• print(List[0])
the list
• print(List[2]) Geeks
Geeks
• Example
• # Creating a Multi-Dimensional List
• # (By Nesting a list inside a List)
• List = [['Geeks', 'For'], ['Geeks']]

• # accessing an element from the


• # Multi-Dimensional List using
• # index number
• print("Accessing a element from a Multi-Dimensional list")
• print(List[0][1])
Output
• print(List[1][0]) Accessing a element from a Multi-Dimensional list
For
Geeks
Accessing values in lists
• Similar to strings, lists can be sliced and concatenated.
• To access values in lists, square brackets are used to slice along
with index or indices to get value stored at that index.

• syntax
• s=list[start:stop:step]
• Example :
• num_list=[1,2,3,4,5,6,7,8,9,10]
• print(“num_list is:”,num_list)
• print(“first elemnent in the list is”,num_list[0])
• print(“num_list[2:5]=”,num_list[2:5])
Output:
• print(“num_list[::2]=”,num_list[::2]) num_list is:
• print(“num_list[1::3]=”,num_list[1::3]) [1,2,3,4,5,6,7,8,9,10]
first elemnent in the list
is 1
num_list[2:5]= [3,4,5]
num_list[::2]= [1,3,5,7,9]
num_list[1::3]= [2,5,8]
Updating values in the lists:
• once created, one or more elements of a list can be easily
updated by giving the slice on the left-hand side of the
assignment operator.

• You can also append new values in the list and remove existing
values from the list using the append( ) method and del
statement respectively.
• Example:
• num_list= [1,2,3,4,5,6,7,8,9,10]

• print(“list is:”,num_list)
• num_list[5]=100
• print(“List after updation is:”,num_list)
• num_list.append(200)
• print(“List after appending a value is: “,num_list)
• del num_list[3]
• print(“List after deleting a value is:”,num_list)
Output:
list is: [1,2,3,4,5,6,7,8,9,10]
List after updation is: [1,2,3,4,5,100,7,8,9,10]
List after appending a value is: [1,2,3,4,5,100,7,8,9,10,200]
List after deleting a value is: [1,2,3,5,100,7,8,9,10,200]
Python List Operations
• The concatenation (+) and repetition (*) operators work in the same
way as they were working with the strings.
• The different operations of list are
• Repetition
• Concatenation
• Length
• Iteration
• Membership
1. Repetition
• The redundancy administrator empowers the rundown components to
be rehashed on different occasions.

• Code

• # repetition of list
• # declaring the list
• list1 = [12, 14, 16, 18, 20]
• # repetition operator *
• l = list1 * 2
• print(l)
• Output:

• [12, 14, 16, 18, 20, 12, 14, 16, 18, 20]
2. Concatenation
• It concatenates the list mentioned on either side of the operator.

• Code

• # concatenation of two lists


• # declaring the lists
• list1 = [12, 14, 16, 18, 20]
• list2 = [9, 10, 32, 54, 86]
• # concatenation operator +
• l = list1 + list2
• print(l) Output:

[12, 14, 16, 18, 20, 9, 10, 32, 54, 86]


3. Length
• It is used to get the length of the list

• Code

• # size of the list


• # declaring the list
• list1 = [12, 14, 16, 18, 20, 23, 27, 39, 40]
• # finding length of the list
• len(list1)
Output:

9
4. Iteration
• The for loop is used to iterate over the list elements.

• Code

• # iteration of the list


• # declaring the list
• list1 = [12, 14, 16, 39, 40]
• # iterating
• for i in list1: Output:
• print(i)
12
14
16
39
40
5. Membership
• It returns true if a particular item exists in a particular list otherwise false.

• Code

• # membership of the list


• # declaring the list
• list1 = [100, 200, 300, 400, 500]
• # true will be printed if value exists
• # and false if not

• print(600 in list1)
• print(700 in list1)
• print(1040 in list1)
Output:

False
• print(300 in list1) False
• print(100 in list1) False
• print(500 in list1) True
True
True
Basic List Operations

tion
Python List methods
• Python List Methods are the built-in methods in lists used to
perform operations on Python lists/arrays.
• Below, we’ve explained all the Python list methods you can use
with Python lists, for example, append(), copy(), insert(), and
more.
Python List methods

Method Description
Used for adding elements to the end of the
append()
List.
copy() It returns a shallow copy of a list
This method is used for removing all items
clear()
from the list.
count() These methods count the elements.
Adds each element of an iterable to the end
extend()
of the List
Returns the lowest index where the element
index()
appears.
Python List methods

Inserts a given element at a given index in a


7 insert()
list.
Removes and returns the last value from the
8 pop()
List or the given index value.
9 remove() Removes a given object from the List.
10 reverse() Reverses objects of the List in place.
Sort a List in ascending, descending, or user-
11 sort()
defined order
Calculates the minimum of all the elements of
12 min()
the List
Calculates the maximum of all the elements of
13 max()
the List
Tuples
• Python Tuple is a collection of objects separated by commas.
• In some ways, a tuple is similar to a Python list in terms of
indexing, nested objects, and repetition but the main difference
between both is Python tuple is immutable, unlike the Python list
which is mutable.
• A tuple is a sequence of immutable objects.
• cannot change the values in a tuple.
• Tuples use parenthesis to define its elements.
Creating Python Tuples
• There are various ways by which you can create a tuple in
Python.
• They are as follows:

• Using round brackets


• With one item
• Tuple Constructor
Creating a Tuple:
• Creating a tuple is as simple as putting different comma-
separated values.
• Optionally you can put these comma-separated values between
parentheses.

Syntax: Tup1=(val1,val2,….)

• Where val (or values) can be an integer, a floating number, a


character, or a string.
• Examples:
Tup1=( ) #creates an empty tuple.
print(Tup1)
output:

• note: no ouput will be displayed.

Tup1=(5) #creates a tuple with single element


print(Tup1)
Output:
•5
Accessing values of tuples:

• Like strings and lists tuples indices also starts with 0.


• The operations performed are slice, concatenate etc.,
• To access values in tuple, slice operation is used along with the index.

• Example :
• 1) Tup1=(1,2,3,4,5,6,7,8,9,10)

• print(“Tup[3:6]=”,Tup1[3:6]) Output:
• print(“Tup[:8]=”,Tup1[:4]) Tup[3:6]=(4,5,6)
Tup[:8]=(1,2,3,4)
• print(“Tup[4:]=”,Tup1[4:])
Tup[4:]=5,6,7,8,9,10)
• print(“Tup[:]=”,Tup1[:]) Tup[:]=(1,2,3,4,5,6,7,8,9,10)
Updating tuples:
• Tuples are immutable objects so we cannot update the values but
we can just extract the values from a tuple to form another tuple.
• Example:
• 1) Tup1=(1,2,3,4,5)

• Tup2=(6,7,8,9,10)
• Tup3=Tup1+Tup2
• print(Tup3)
Output:
(1,2,3,4,5,6,7,8,9,10)
Deleting elements of a tuple
• Deleting a single element in a tuple is not possible as we know a tuple
is an immutable object.
• Hence there is another option to delete a single element of a tuple i.e..,
you can create a new tuple that has all elements in your tuple except the
ones you don’t want.
• Example:
• 1) Tup1=(1,2,3,4,5)
Output:
Traceback (most recent call last):
• del Tup1[3] File "test.py", line 9, in <module>
• print Tup1 del Tup1[3]
Type error: „tuple‟ object doesn‟t support item
deletion
Nested Tuples in Python
• A nested tuple is a Python tuple that has been placed inside of
another tuple.
• Let's have a look at the following 8-element tuple.
• tuple = (12, 23, 36, 20, 51, 40, (200, 240, 100))
• This last element, which consists of three items enclosed in
parenthesis, is known as a nested tuple since it is contained
inside another tuple.
• The name of the main tuple with the index value, tuple[index], can
be used to obtain the nested tuple, and we can access each item of
the nested tuple by using tuple[index-1][index-2].
Example of a Nested Tuple
• # Python program to create a nested tuple
• # Creating a nested tuple of one element only
• employee = ((10, "Itika", 13000),)
• print(employee)

• # Creating a multiple-value nested tuple


• employee = ((10, "Itika", 13000), (24, "Harry", 15294), (15, "Naill",
20001), (40, "Peter", 16395))
• print(employee)
Output:

((10, 'Itika', 13000),)


((10, 'Itika', 13000), (24, 'Harry', 15294), (15, 'Naill', 20001), (40, 'Peter', 16395))
Differences between List and Tuple in Python

Sno LIST TUPLE


1 Lists are mutable Tuples are immutable
The implication of iterations is The implication of iterations is
2
Time-consuming comparatively Faster
The list is better for performing
A Tuple data type is appropriate for
3 operations, such as insertion and
accessing the elements
deletion.
Tuple consumes less memory as
4 Lists consume more memory
compared to the list
Tuple does not have many
5 Lists have several built-in methods
built-in methods.

Unexpected changes and errors are Because tuples don’t change


6
more likely to occur they are far less error-prone.
Dictionaries in Python
• A Python dictionary is a data structure that stores the value in key:
value pairs.
• Dictionaries and lists share the following characteristics:
• Both are mutable.
• Both are dynamic. They can grow and shrink as needed.
• Both can be nested. A list can contain another list. A dictionary can contain
another dictionary. A dictionary can also contain a list, and vice versa.
• Dictionaries differ from lists primarily in how elements are accessed:
• List elements are accessed by their position in the list, via indexing.
• Dictionary elements are accessed via keys.
Defining a Dictionary
• Dictionaries are Python’s implementation of a data structure that is
more generally known as an associative array.
• A dictionary consists of a collection of key-value pairs.
• Each key-value pair maps the key to its associated value.
• Define a dictionary by enclosing a comma-separated list of key-
value pairs in curly braces ({}). A colon (:)
• Python Dictionary Syntax

dict_var = {key1 : value1, key2 : value2, …..}


Create a Dictionary
• In Python, a dictionary can be created by placing a sequence of
elements within curly {} braces, separated by a ‘comma’.
• The dictionary holds pairs of values, one being the Key and
the other corresponding pair element being its Key:value.
• Values in a dictionary can be of any data type and can be
duplicated, whereas keys can’t be repeated and must
be immutable.
• Dict = {1: 'Geeks', 2: 'For', 3: 'Geeks'}
• print("\nDictionary with the use of Integer Keys: ")
• print(Dict)

• Dict = {'Name': 'Geeks', 1: [1, 2, 3, 4]}


• print("\nDictionary with the use of Mixed Keys: ")
• print(Dict)

Output
Dictionary with the use of Integer Keys:
{1: 'Geeks', 2: 'For', 3: 'Geeks'}

Dictionary with the use of Mixed Keys:


{'Name': 'Geeks', 1: [1, 2, 3, 4]}
• Complexities for Creating a Dictionary:
• Time complexity: O(len(dict))
• Space complexity: O(n)
• Python provides the built-in function dict() method which is
also used to create the dictionary.
• The empty curly braces {} is used to create empty dictionary.
Accessing the dictionary values
• The keys of the dictionary can be used to obtain the values
because they are unique from one another.
• Example:

Employee = {"Name": "Dev", "Age": 20, "salary":45000, "Company": "WIPRO"}


print(type(Employee))
print("printing Employee data .... ")
print("Name : %s" %Employee["Name"])
print("Age : %d" %Employee["Age"])
print("Salary : %d" %Employee["salary"])
print("Company : %s" %Employee["Company"])
• Output
• printing Employee data ....
• Name : Dev
• Age : 20
• Salary : 45000
• Company : WIPRO
• Python provides us with an alternative to use the get() method
to access the dictionary values.
• It would give the same result as given by the indexing.
Adding Dictionary Values
• The dictionary is a mutable data type, and utilizing the right
keys allows you to change its values.
• Dict[key] = value and the value can both be modified.
• An existing value can also be updated using the update()
method.
• # Creating an empty Dictionary
• Dict = {}
• print("Empty Dictionary: ")
• print(Dict)
• # Adding set of values
# with a single Key
• # Adding elements to dictionary on
e at a time # The Emp_ages doesn't exist to dictionary
Dict['Emp_ages'] = 20, 33, 24
• Dict[0] = 'Peter' print("\nDictionary after adding 3 elements: ")
• Dict[2] = 'Joseph'
• Dict[3] = 'Ricky' print(Dict)
• print("\nDictionary after adding 3 e
# Updating existing Key's Value
lements: ")
Dict[3] = 'JavaTpoint'
• print(Dict) print("\nUpdated key value: ")
• print(Dict)
• Output

• Empty Dictionary:
• {}

• Dictionary after adding 3 elements:


• {0: 'Peter', 2: 'Joseph', 3: 'Ricky'}

• Dictionary after adding 3 elements:


• {0: 'Peter', 2: 'Joseph', 3: 'Ricky', 'Emp_ages': (20, 33, 24)}

• Updated key value:


• {0: 'Peter', 2: 'Joseph', 3: 'JavaTpoint', 'Emp_ages': (20, 33, 24)}
Accessing a Dictionary
• The most common way to access key values from a dictionary is
via indexing.

dict_1 = {'one': 1, 'two': 2, 'three': 3, 'four': 4, 'five': 5}

print("Access Key 'one': ", dict_1['one']) # access value at key 'one’


print("Access Key 'five': ", dict_1['five']) # access value at key 'five’
print("Access Key 'three': ", dict_1['three']) # access value at key 'three'

Output

accessing a dictionary
• Accessing Values
• The main and common way to access dictionary values is via indexing.
• However, this approach is dangerous because if we try to access the
value of a key that doesn’t exist, then Python will raise a KeyError
exception.

• dict_1 = {'one': 1, 'two': 2, 'three': 3, 'four': 4, 'five': 5}


• print("Access Key: ", dict_1['six']) # access value at key 'six', which
doesn't exist
• Output

• access_Value_missing_key
Accessing Keys
• The Python dictionary just has one method that is solely used to
return keys from a dictionary.

• #1) d.keys()

• This method returns all the keys in the dictionary as a dictionary


view object.
• dict_keys([key1, key2,....,keyN])

• Just like d.value(), this returned object can be converted into a set,
tuple, list, or directly iterated through, based on need.
• Accessing Key-Value Pairs
• At times it is necessary to access dictionary key-value pairs.
• if we want to compute the dictionary values, and create a new
dictionary with the new values but maintaining the keys.

• The Python dictionary has a method that is solely used for this purpose.

• #1) d.item()

• This method returns each key-value pair of a dictionary as a dictionary


view object of tuples.

• dict_items([(value1,key1),(value1,key1),...,(valueN,keyN)])
Update A Dictionary
• We can change the value of a key in a dictionary.
• The most common way is via indexing.

• dict_1 = {'one': 1, 'two': 2, 'three': 3, 'four': 4, 'five': 5}


• dict_new = dict_1.copy() # make a copy to work with
• print("Dict before update: ", dict_new)

• dict_new['one'] = '01' # change value of key 'one'
• dict_new['two'] = '02' # change value of key 'two'
• Output

• print("Dict after update: ", dict_new) updating a dictionary


• d.update(b)
• This method adds all objects from dictionary b into dictionary d.

• dict_1 = {'one': 1, 'two': 2, 'three': 3, 'four': 4, 'five': 5}


• dict_new = dict_1.copy() # make a copy to work with
• print("Dict before update: ", dict_new)

• dict_new.update(one='01', two='02') #update the values at key 'one'
and 'two'
• print("Dict after update: ", dict_new)
Output

d.update(b) - output
Delete From A Dictionary

• Most dictionary methods that delete elements from a dictionary


also return these elements.
• The del keyword can be used to delete an element by key
without a return.

• Deleting Elements using del Keyword


• The items of the dictionary can be deleted by using
the del keyword as given below.
Employee = {"Name": "David", "Age": 30, "salary":55000,"Company":"
WIPRO"}
print(type(Employee))
print("printing Employee data .... ")
print(Employee)
print("Deleting some of the employee data")
del Employee["Name"]
del Employee["Company"]
Output
print("printing the modified information ")
print(Employee) <class 'dict'>
printing Employee data ....
print("Deleting the dictionary: Employee"); {'Name': 'David', 'Age': 30, 'salary': 55000, 'Company':
'WIPRO'}
del Employee Deleting some of the employee data
print("Lets try to print it again "); printing the modified information
{'Age': 30, 'salary': 55000}
print(Employee) Deleting the dictionary: Employee
Lets try to print it again
• Deleting Elements using pop() Method
• A dictionary is a group of key-value pairs in Python.
• You can retrieve, insert, and remove items using this unordered,
mutable data type by using their keys.
• The pop() method is one of the ways to get rid of elements from a
dictionary.
• to remove items from a Python dictionary using the pop() method.
• The value connected to a specific key in a dictionary is removed
using the pop() method, which then returns the value.
• The key of the element to be removed is the only argument
needed.
• # Creating a Dictionary
• Dict1 = {1: 'JavaTpoint', 2: 'Educational', 3: 'Website'}
• # Deleting a key
• # using pop() method
• pop_key = Dict1.pop(2)
• print(Dict1)
• Output

• {1: 'JavaTpoint', 3: 'Website'}


Python Dictionary Methods
Name Syntax Description

items d.items() Returns each key-value pair of a dictionary, d, as


a tuple.
get d.get(k[, default]) Returns the value associated with the key(k). If k
doesn’t exist, returns default if defined,
otherwise returns None.
keys d.keys() Returns all the keys defined in the dictionary, d
values d.values() Returns all the values in the dictionary, d
pop d.pop(k[, default]) Removes the key(k) from the dictionary and
returns its value, else return default if k not in
the dictionary, d.
popitem d.popitem() Returns and removes a key-value pair from the
dictionary, d, in a LIFO order.
clear d.clear() Remove all elements from the dictionary, d
update d.update(b) Add all objects from dictionary b to dictionary
d.
copy d.copy() Returns a shallow copy of the dictionary, d
setdefault d.setdefault(k[,def Returns the value associated with the key, k, if
ault]) exist, else returns default and sets key, k, to
default in the dictionary, d
fromkeys d.fromkeys(s[, Create a new dictionary with keys from the
value]) sequence, s, and values set to value.
Difference between a List and a Dictionary
List Dictionary

The dictionary is a hashed structure


The list is a collection of index value
of the key and value pairs.
pairs like ArrayList in Java and
Vectors in C++.

The dictionary is created by placing


The list is created by placing elements elements in { } as “key”:”value”, each
in [ ] separated by commas “, “ key-value pair is separated by
commas “, “
The indices of the list are integers The keys of the dictionary can be of
starting from 0. any immutable data type.
The elements are accessed via
The elements are accessed via key.
indices.

They are unordered in python 3.6


The order of the elements entered is
and below and are ordered in python
maintained.
3.7 and above.

Dictionaries cannot contain duplicate


Lists can duplicate values since each
keys but can contain duplicate values
values have unique index.
since each value has unique key.
Average time taken to search a Average time taken to search a
value in list takes O[n]. key in dictionary takes O[1].

Average time to delete a certain Average time to delete a certain


value from a list takes O[n]. key from a dictionary takes O[1].

You might also like