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

PPS Notes (Unit 2) gcoea

pps

Uploaded by

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

PPS Notes (Unit 2) gcoea

pps

Uploaded by

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

Unit 2

Basics of Data Structures using Python and C Programming

Data Structure: A data structure is a storage that is used to store and organize data. It is a
way of arranging data on a computer so that it can be accessed and updated efficiently.
A data structure is not only used for organizing the data. It is also used for processing,
retrieving, and storing data.

List in Python:
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 of the list in Python


Here we are creating a Python List using [].

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.

List elements can be accessed by the assigned index. In python starting index of the list,
sequence is 0 and the ending index is (if N elements are there) N-1.
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 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


A list may contain duplicate values with their distinct positions and hence, multiple distinct
or duplicate values can be passed as a sequence at the time of list creation.

# 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']

Getting the size of Python list


Python len() is used to get the length of the list.

# Creating a List
List1 = []
print(len(List1))

# Creating a List of numbers


List2 = [10, 20, 14]
print(len(List2))

Output
0
3

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

Example 2: Accessing elements from a multi-dimensional list

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

Output
Accessing a element from a Multi-Dimensional list

For
Geeks

Negative indexing
In 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.

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
Tuple in Python:
Python Tuple is a collection of Python Programming objects much like a list. The sequence
of values stored in a tuple can be of any type, and they are indexed by integers. Values of a
tuple are syntactically separated by ‘commas‘. Although it is not necessary, it is more
common to define a tuple by closing the sequence of values in parentheses. This helps in
understanding the Python tuples more easily.
Creating a Tuple
In Python Programming, tuples are created by placing a sequence of values separated by
‘comma’ with or without the use of parentheses for grouping the data sequence.
Python Program to Demonstrate the Addition of Elements in a Tuple.

# Creating an empty Tuple


Tuple1 = ()
print("Initial empty Tuple: ")
print(Tuple1)

# Creating a Tuple
# with the use of string
Tuple1 = ('Geeks', 'For')
print("\nTuple with the use of String: ")
print(Tuple1)

# Creating a Tuple with


# the use of list
list1 = [1, 2, 4, 5, 6]
print("\nTuple using List: ")
print(tuple(list1))

Output:
Initial empty Tuple:
()

Tuple with the use of String:


('Geeks', 'For')

Tuple using List:


(1, 2, 4, 5, 6)

Creating a Tuple with Mixed Datatypes.


Python Tuples can contain any number of elements and of any datatype (like strings,
integers, list, etc.). Tuples can also be created with a single element, but it is a bit tricky.
Having one element in the parentheses is not sufficient, there must be a trailing ‘comma’ to
make it a tuple.
Python

# Creating a Tuple
# with Mixed Datatype
Tuple1 = (5, 'Welcome', 7, 'Geeks')
print("\nTuple with Mixed Datatypes: ")
print(Tuple1)

# Creating a Tuple
# with nested tuples
Tuple1 = (0, 1, 2, 3)
Tuple2 = ('python', 'geek')
Tuple3 = (Tuple1, Tuple2)
print("\nTuple with nested tuples: ")
print(Tuple3)

# Creating a Tuple
# with repetition
Tuple1 = ('Geeks',) * 3
print("\nTuple with repetition: ")
print(Tuple1)

Output:
Tuple with Mixed Datatypes:
(5, 'Welcome', 7, 'Geeks')

Tuple with nested tuples:


((0, 1, 2, 3), ('python', 'geek'))

Tuple with repetition:


('Geeks', 'Geeks', 'Geeks')

Concatenation of Tuples
Concatenation of tuple is the process of joining two or more Tuples. Concatenation is done
by the use of ‘+’ operator. Concatenation of tuples is done always from the end of the
original tuple. Other arithmetic operations do not apply on Tuples.
Note- Only the same datatypes can be combined with concatenation, an error arises if a list
and a tuple are combined.
# Concatenation of tuples
Tuple1 = (0, 1, 2, 3)
Tuple2 = ('Geeks', 'For', 'Geeks')

Tuple3 = Tuple1 + Tuple2

# Printing first Tuple


print("Tuple 1: ")
print(Tuple1)

# Printing Second Tuple


print("\nTuple2: ")
print(Tuple2)

# Printing Final Tuple


print("\nTuples after Concatenation: ")
print(Tuple3)
Output:
Tuple 1:
(0, 1, 2, 3)

Tuple2:
('Geeks', 'For', 'Geeks')

Tuples after Concatenation:


(0, 1, 2, 3, 'Geeks', 'For', 'Geeks')

# Creating a Tuple with


# the use of Strings
Tuple = ('Geeks', 'For')
print("\nTuple with the use of String: ")
print(Tuple)

# Creating a Tuple with


# the use of list
list1 = [1, 2, 4, 5, 6]
print("\nTuple using List: ")
Tuple = tuple(list1)

# Accessing element using indexing


print("First element of tuple")
print(Tuple[0])

# Accessing element from last


# negative indexing
print("\nLast element of tuple")
print(Tuple[-1])
print("\nThird last element of tuple")
print(Tuple[-3])

Output
Tuple with the use of String:

('Geeks', 'For')

Tuple using List:

First element of tuple

Last element of tuple

Third last element of tuple

Dictionary in Python:
A Python dictionary is a data structure that stores the value in key: value pairs.
Example: Here, The data is stored in key: value pairs in dictionaries, which makes it easier
to find values.
Python
Dict = { 1: 'Geeks', 2: 'For', 3: 'Geeks'}
print(Dict)

Output
{1: 'Geeks', 2: 'For', 3: 'Geeks'}

Python Dictionary Syntax


dict_var = {key1 : value1, key2 : value2, …..}
What is a Dictionary in Python?
Dictionaries in Python is a data structure, used to store values in key: value format. This
makes it different from lists, tuples, and arrays as in a dictionary each key has an associated
value.
Note: As of Python version 3.7, dictionaries are ordered and can not contain duplicate keys.
How to 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.
Note – Dictionary keys are case sensitive, the same name but different cases of Key will be
treated distinctly.
The code demonstrates creating dictionaries with different types of keys. The first dictionary
uses integer keys, and the second dictionary uses a mix of string and integer keys with
corresponding values. This showcases the flexibility of Python dictionaries in handling
various data types as keys.

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]}

Different Ways to Create a Python Dictionary


The code demonstrates different ways to create dictionaries in Python. It first creates an
empty dictionary, and then shows how to create dictionaries using the dict() constructor with
key-value pairs specified within curly braces and as a list of tuples.

Dict = {}
print("Empty Dictionary: ")
print(Dict)

Dict = dict({1: 'Geeks', 2: 'For', 3: 'Geeks'})


print("\nDictionary with the use of dict(): ")
print(Dict)

Dict = dict([(1, 'Geeks'), (2, 'For')])


print("\nDictionary with each item as a pair: ")
print(Dict)

Output

Empty Dictionary:

{}
Dictionary with the use of dict():

{1: 'Geeks', 2: 'For', 3: 'Geeks'}

Dictionary with each item as a pair:

{1: 'Geeks', 2: 'For'}

Adding Elements to a Dictionary


The addition of elements can be done in multiple ways. One value at a time can be added to a
Dictionary by defining value along with the key e.g. Dict[Key] = ‘Value’.
Updating an existing value in a Dictionary can be done by using the built-
in update() method. Nested key values can also be added to an existing Dictionary.
Note- While adding a value, if the key-value already exists, the value gets updated otherwise
a new Key with the value is added to the Dictionary.
Example: Add Items to a Python Dictionary with Different DataTypes
The code starts with an empty dictionary and then adds key-value pairs to it. It demonstrates
adding elements with various data types, updating a key’s value, and even nesting
dictionaries within the main dictionary. The code shows how to manipulate dictionaries in
Python.
Python

Dict = {}
print("Empty Dictionary: ")
print(Dict)
Dict[0] = 'Geeks'
Dict[2] = 'For'
Dict[3] = 1
print("\nDictionary after adding 3 elements: ")
print(Dict)

Output

Empty Dictionary:

{}

Dictionary after adding 3 elements:

{0: 'Geeks', 2: 'For', 3: 1}

Accessing Elements of a Dictionary


To access the items of a dictionary refer to its key name. Key can be used inside square
brackets.

Access a Value in Python Dictionary


The code demonstrates how to access elements in a dictionary using keys. It accesses and
prints the values associated with the keys ‘name’ and 1, showcasing that keys can be of
different data types (string and integer).

You might also like