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

UNIT 4 Py

Uploaded by

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

UNIT 4 Py

Uploaded by

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

UNIT- IV

LIST:
Python Lists are just like dynamically sized arrays, declared in other languages (vector in
C++ and Array List in Java). In simple language, a list is a collection of things, enclosed in [ ]
and separated by commas.

Eg:
Var = ["Geeks", "for", "Geeks"]
print(Var)
O/P
["Geeks", "for", "Geeks"]
Creating List
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 1: Creating a list in Python
# Creating a List
List = []
print("Blank List: ")
print(List)

# Creating a List of numbers


List = [10, 20, 14]
print("\nList of numbers: ")
print(List)

# Creating a List of strings and accessing


# using index
List = ["Geeks", "For", "Geeks"]
print("\nList Items: ")
print(List[0])
print(List[2])

Output
Blank List:
[]

List of numbers:
[10, 20, 14]
List Items:
Geeks
Geeks
Example 2: Creating a list with multiple distinct or duplicate elements
# Creating a List with the use of Numbers
# (Having duplicate values)
List = [1, 2, 4, 4, 3, 3, 3, 6, 5]
print("\nList with the use of Numbers: ")
print(List)

# Creating a List with mixed datatype values


# (Having numbers and strings)
List = [1, 2, 'Geeks', 4, 'For', 6, 'Geeks']
print("\nList with the use of Mixed Values: ")
print(List)

Output
List with the use of Numbers:
[1, 2, 4, 4, 3, 3, 3, 6, 5]

List with the use of Mixed Values:


[1, 2, 'Geeks', 4, 'For', 6, 'Geeks']

Accessing Values in 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 1: Accessing elements from list


# 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")
print(List[0])
print(List[2])

Output

Accessing a element from the list


Geeks
Geeks
Negative indexing
n Python, negative sequence indexes represent positions from the end of the List. Instead of
having to compute the offset as in List[len(List)-3], it is enough to just write List[-3].
Negative indexing means beginning from the end, -1 refers to the last item, -2 refers to the
second-last item, etc.
Example
List = [1, 2, 'Geeks', 4, 'For', 6, 'Geeks']
print("Accessing element using negative indexing")

# print the last element of list


print(List[-1])

# print the third last element of list


print(List[-3])

Output
Accessing element using negative indexing
Geeks
For

Nested Lists

In Python, nested lists are lists that contain other lists as their elements. They can be useful
for storing and manipulating complex data structures, such as matrices, graphs, or trees.

Creating Nested Lists

In order to create a nested list, you can simply use square brackets [] to enclose one or more
lists inside another list.

Example:
nested_list = [[1, 2, 3], ["a", "b", "c"], [True, False, None]]
print(nested_list)

Output:
[[1, 2, 3], ['a', 'b', 'c'], [True, False, None]]
Example:
nested_list = [
['puppy', 'kitty', 'petey'],
[2023, 2024, 2025],
[True, False]
]

# Printing the indices and the elements of a nested list


for i, sublist in enumerate(nested_list):
for j, element in enumerate(sublist):
print(f"nested_list[{i}][{j}] = {element}")
Output:
nested_list[0][0] = puppy
nested_list[0][1] = kitty
nested_list[0][2] = petey
nested_list[1][0] = 2023
nested_list[1][1] = 2024
nested_list[1][2] = 2025
nested_list[2][0] = True
nested_list[2][1] = False

Basic List Operations List Methods:

In Python, lists are versatile data structures that come with a variety of operations and
methods to manipulate them. Here’s a rundown of common list operations and methods:

Basic List Operations


1. Creation:
o Using square brackets: my_list = [1, 2, 3]
o Using the list() constructor: my_list = list((1, 2, 3))
2. Accessing Elements:
o Indexing: my_list[0] (first element)
o Slicing: my_list[1:3] (elements from index 1 to 2)
3. Length:
o len(my_list) to get the number of elements.
4. Concatenation:
o Using the + operator: list1 + list2
5. Repetition:
o Using the * operator: my_list * 2
6. Membership:
o Using in: if 1 in my_list:
7. Iteration:
o Using a loop: for item in my_list:
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

A tuple is a collection similar to a Python list. The primary difference is that we cannot
modify a tuple once it is created.

Creating a Python Tuple

We create a tuple by placing items inside parentheses ().

Example

numbers = (1, 2, -5)


print(numbers)

Output:
(1, 2, -5)

Example
# tuple including string and integer
mixed_tuple = (2, 'Hello', 'Python')
print(mixed_tuple)

Output:
(2, 'Hello', 'Python')

Tuple Characteristics
Tuples are:
 Ordered - They maintain the order of elements.
 Immutable - They cannot be changed after creation.
 Allow duplicates - They can contain duplicate values.

Accessing Tuple

Each item in a tuple is associated with a number, known as a index.


The index always starts from 0, meaning the first item of a tuple is at index 0, the second item
is at index 1, and so on.

Accessing Items Using Index

languages = ('Python', 'Swift', 'C++')

# access the first item


print(languages[0])

# access the third item


print(languages[2])

Output:

Python
C++

Updating tuple

In Python, tuples are immutable, meaning you cannot change their content once they are
created. However, you can create a new tuple that reflects the changes you want. Here are a
few ways to "update" a tuple:

1. Reassigning a Tuple
You can create a new tuple by concatenating or slicing the original tuple.
# Original tuple
original_tuple = (1, 2, 3, 4)

# Create a new tuple with the updated value


updated_tuple = original_tuple[:2] + (99,) + original_tuple[3:]

print(updated_tuple)

Output:
(1, 2, 99, 4)

2. Using List Conversion


Convert the tuple to a list, update the list, and then convert it back to a tuple.

# Original tuple
original_tuple = (1, 2, 3, 4)

# Convert to list, update, and convert back to tuple


temp_list = list(original_tuple)
temp_list[2] = 99 # Update the value
updated_tuple = tuple(temp_list)

print(updated_tuple)

Output:
(1, 2, 99, 4)

Deleting Tuples

We cannot delete individual items of a tuple. However, we can delete the tuple itself using
the del statement.

Example

animals = ('dog', 'cat', 'rat')

# deleting the tuple


del animals
print(“Table Deleted”)

Output:
Table Deleted

Nested Tuples in Python


A nested tuple is a Python tuple that has been placed inside of another 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
1. # Python program to create a nested tuple
2.
3. # Creating a nested tuple of one element only
4. employee = ((10, "Itika", 13000),)
5. print(employee)
6.
7. # Creating a multiple-value nested tuple
8. employee = ((10, "Itika", 13000), (24, "Harry", 15294), (15, "Naill", 20001), (40, "Pet
er", 16395))
9. print(employee)
Output:
((10, 'Itika', 13000),)
((10, 'Itika', 13000), (24, 'Harry', 15294), (15, 'Naill', 20001), (40, 'Peter', 16395))

Difference Between List and Tuple


Lists and Tuples in Python are two classes of Python Data Structures. The list structure is
dynamic, and readily changed whereas the tuple structure is static and cannot be changed.
This means that the tuple is generally faster than the list. Lists are denoted by square brackets
and tuples are denoted with parenthesis.

Differences between List and Tuple in Python


Sn
o LIST TUPLE

1 Lists are mutable Tuples are immutable

The implication of iterations is Time- The implication of iterations is


2
consuming comparatively Faster

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

Tuple consumes less memory as


4 Lists consume more memory
compared to the list

Tuple does not have many built-in


5 Lists have several built-in methods
methods.

Unexpected changes and errors are more Because tuples don’t change they
6
likely to occur are far less error-p
Dictionary
A Python dictionary is a collection of items, similar to lists and tuples. However, unlike lists
and tuples, each item in a dictionary is a key-value pair (consisting of a key and a value).
Create a Dictionary
We create a dictionary by placing key: value pairs inside curly brackets {}, separated by
commas. For example,
Explain
# creating a dictionary
country_capitals = {
"Germany": "Berlin",
"Canada": "Ottawa",
"England": "London"
}

# printing the dictionary


print(country_capitals)
Output
{'Germany': 'Berlin', 'Canada': 'Ottawa', 'England': 'London'}

Access Dictionary Items


We can access the value of a dictionary item by placing the key inside square brackets.
country_capitals = {
"Germany": "Berlin",
"Canada": "Ottawa",
"England": "London"
}

# access the value of keys


print(country_capitals["Germany"]) # Output: Berlin
print(country_capitals["England"]) # Output: London

Updating Items to a Dictionary


We can add an item to a dictionary by assigning a value to a new key. For example,
country_capitals = {
"Germany": "Berlin",
"Canada": "Ottawa",
}

# add an item with "Italy" as key and "Rome" as its value


country_capitals["Italy"] = "Rome"

print(country_capitals)
Output
{'Germany': 'Berlin', 'Canada': 'Ottawa', 'Italy': 'Rome'}

Deleting Dictionary Items


We can use the del statement to remove an element from a dictionary. For example,
country_capitals = {
"Germany": "Berlin",
"Canada": "Ottawa",
}

# delete item having "Germany" key


del country_capitals["Germany"]

print(country_capitals)
Output
{'Canada': 'Ottawa'}

Python Dictionary Functions and Methods


Here are some of the commonly used dictionary methods.
Function Description

pop() Removes the item with the specified key.

update() Adds or changes dictionary items.

clear() Remove all the items from the dictionary.

keys() Returns all the dictionary's keys.


values() Returns all the dictionary's values.

get() Returns the value of the specified key.

popitem() Returns the last inserted key and value as a tuple.

copy() Returns a copy of the dictionary.

Difference between a List and a Dictionary


The following table shows some differences between a list and a dictionary in Python:

List Dictionary

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

The list is created by placing The dictionary is created by placing elements


elements in [ ] separated by commas in { } as “key”:”value”, each key-value pair is
“, “ separated by commas “, “

The indices of the list are integers The keys of the dictionary can be of any
starting from 0. immutable data type.

The elements are accessed via


The elements are accessed via key.
indices.

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

Dictionaries cannot contain duplicate keys but can


Lists can duplicate values since each
contain duplicate values since each value has
values have unique index.
unique key.

Average time taken to search a value Average time taken to search a key in dictionary
List Dictionary

in list takes O[n]. takes O[1].

Average time to delete a certain Average time to delete a certain key from a
value from a list takes O[n]. dictionary takes O[1].

You might also like