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

Week8(Data Structures (List, Strings, Sequence Iteration & Loops))

computer python

Uploaded by

rahidsaleemcool
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
5 views

Week8(Data Structures (List, Strings, Sequence Iteration & Loops))

computer python

Uploaded by

rahidsaleemcool
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
You are on page 1/ 33

Computer Programming [108403]

Using Python

Data Structures (List, Sequence Iteration &


Loops )

Note:- some material of the course has been adopted from freely available public sources
12/28/2024
What is a Data Structure?
 Organizing, managing and storing data is important as it

enables easier access and efficient modifications.


 Data Structures allows you to organize your data in such

a way that enables you to store collections of data,


relate them and perform operations on them
accordingly.
 Each data structure provides a particular way of

organizing data so it can be accessed efficiently,


depending on your use case.
 Python comes with an extensive set of data structures

in its standard library.


2 12/28/2024
Types of Data Structures : Overview

Study and familiarize yourself with


these type of data structures

3 12/28/2024
List (indexing)
 Lists are used to store data of different data types
in a sequential manner.
 There are addresses assigned to every element of
the list, which is called as Index.
 The index value starts from 0 and goes on until
the last element.

4 12/28/2024
List (creation & modification)
 List can contain data of different datatypes
 A list of string, a float, an integer, and another list

 Lists Are Mutable

5 12/28/2024
List Operations

12/28/2024
6
List Operations

7 12/28/2024
Membership operator (in)
 Determines whether a given value is present in a sequence such
as a string, array, list, or tuple.
 Returns True if value is present otherwise return False.

Identity operator (is) ?


8 12/28/2024
List Arguments & Aliasing

9 12/28/2024
Alias: Example
• Execute the following: • Execute the following:
>>> x = [5, 6, 5, 9, 10] >>> x = [5, 6, 5, 9, 10]
>>> y = x[:] >>> y = x
>>> y[1] = 7 >>> y[1] = 7
• What is x[1]? • What is x[1]?
A: 7 A: 7
B: 5 B: 5
C: 6 C: 6
D: ERROR D: ERROR
E: I don’t know E: I don’t know
Comparison of String & List

String List

• s = 'abc d' • x = [5, 6, 5, 9, 15, 23]


0 1 2 3 4 0 1 2 3 4 5
a b c d 5 6 5 9 15 23

• Put characters in quotes • Put values inside [ ]


 Use \' for quote character  Separate by commas
• Access characters with • Access values with []
[] s[0] is 'a'  x[0] is 5
 s[5] causes an error  x[6] causes an error
 s[0:2] is 'ab'  x[0:2] is [5, 6]
 s[2:] is 'c d'  x[3:] is [9, 15, 23]
11
Iterating Through a string/List

12/28/2024
String Formatting
F-string Method:

>>n = ‘good’
>>print(f“Its always {n} to learn.")

Output:
Its always good to learn.

>>a = "Islamabad"
>>print(f"""Avionics Engineering
>>Institute of space Technology,
>>{a}.""")

Output:
Lists Methods
x = [5, 6, 5, 9, 15, 23]

• <list>.index(<value>)
 Return position of the value
 ERROR if value is not there
 x.index(9) evaluates to 3
• <list>.count(<value>)
 Returns number of times value appears in list
 x.count(5) evaluates to 2
Things that Work for All Sequences

s = ‘slithy’ x = [5, 6, 9, 6, 15, 5]


s.index(‘s’) → 0 methods x.index(5) → 0
s.count(‘t’) → 1 x.count(6) → 2
len(s) → 6 built-in fn. len(x) → 6
s[4] → “h” x[4] → 15
s[1:3] → “li” slicing x[1:3] → [6, 9]
s[3:] → “thy” x[3:] → [6, 15, 5]
s[–2] → “h” x[–2] → 15
s + ‘ toves’ x + [1, 2]
operators

→ “slithy toves” → [5, 6, 9, 6, 15, 5, 1, 2]


s*2 x*2
→ “slithyslithy” → [5, 6, 9, 6, 15, 5, 5, 6, 9, 6, 15, 5]
List Assignment
• Format: • x = [5, 7,4,-2]
0 1 2
<var>[<index>] = <value> 3
5
7 4 -2
 Reassign at index
 Affects folder contents • x[1] = 8
 Variable is unchanged
id1
0 5
x id1 1 7
2 4
3 -2
List Assignment
• Format: • x = [5, 7,4,-2]
0 1 2
<var>[<index>] = <value> 3
5 X7 4 -2
 Reassign at index
8
 Affects contents • x[1] = 8
 Variable is unchanged
• Strings cannot do this
0 5
 s = 'Hello World!' 1 x7 8
 s[0] = 'J' ERROR 2 4
3 -2
 String are immutable
Lists and Expressions
• List brackets [] can • Execute the following:
contain expressions >>> a = 5
• This is a list >>> b = 7
expression >>> x = [a, b, a+b]
 Python must • What is x[2]?
evaluate it >>> 12
 Evaluates each
expression
 Puts the value in
the list
• Example:
>>> a =
[1+2,3+4,5+6]
List Methods Can Alter the List

x = [5, 6, 5, 9]
• <list>.append(<value>)
 Adds a new value to the end of list
 x.append(-1) changes the list to [5, 6, 5, 9, -1]
• <list>.insert(<index>,<value>)
 Puts value into list at specified index; shifts rest
of list right
 x.insert(2,-1) changes the list to [5, 6, -1, 5, 9]
• <list>.sort()
List insert method Example
• Execute the following:
>>> x = [5, 6, 5, 9, 10]
>>> x[3] = -1
>>> x.insert(1, 2)
• What is x[4]?

A: 10
B: 9
C: -1
D: ERROR
E: I don’t know
Lists and Functions: Swap
def swap(b, h, k):
"""Procedure swaps b[h] and b[k] in b
Precondition: b is a mutable list, h
and k are valid positions in the list""”
1 temp= b[h]
2 b[h]= b[k]
3 b[k]= temp 0 5
What gets printed? 1 4
A: 5 2 7
x = [5,4,7,6,5] B: 6 3 6
swap(x, 3, 4) C: Something else 4 5
print x[3] D: I don’t know
Operations on Strings
text.split(<sep>): return a list <sep>.join(words):
of the words in text (separated concatenate the items in the
by , or whitespace by default) list of strings words,
separated by <sep>.
text = 'A sentence is just\na list of words'
words = text.split() [‘A’, ‘sentence’, ‘is’, ‘just’, ‘a’, …]
returns a list of lines = text.split('\n')
two strings ‘A-sentence-is-just-a…’
print('-'.join(words))
The Map Function
• To process a list, you often want to do the same thing to
each item in the list. One way to do this:
 The map function: Call the function once for each
item in the list, with the list
map(⟨function⟩, ⟨list⟩) item as the argument, and put
the return values into a list.
The Map Function
• map(⟨function⟩, ⟨list⟩)
 Function must have map(f, x)
exactly 1 parameter
 Otherwise, get an
error
[f(x[0]), f(x[1]), …, f(x[n–1])]
 Returns a new list

calls the function f


once for each
item
map(len, ['a', 'bc', 'defg'])
Returns object which can be
converted to a list [1, 2, 4]
Beware of Infinite Looping

b = [1, 2, 3]
for a in b: A: never prints b CORRECT*
b.append(a) B: [1, 2, 3, 1, 2, 3]
C: [1, 2, 3]
INFINITE D: I do not know
LOOP!

print b * Runs out of memory eventually,


then probably throws an error.
Working with Lists: For Loops and Conditionals

def num_ints(thelist):
"""Returns: the number of ints in the list
Precondition: thelist is a list of any mix of types"""
result = 0
for x in thelist:
if type(x) == int:
result = result+1 Body
return result
Working with Lists: For Loops and Conditionals

def add_one(thelist):
"""(Procedure) Adds 1 to every element in thelist
Precondition: thelist is a list of all numbers
(either floats or ints)"""
for x in thelist: What gets printed?
x = x+1 A: [5, 4, 7]
B: [5, 4, 7, 5, 4, 7]
>>> a = [5, 4, 7] C: [6, 5, 8]
>>> add_one(a) D: Error
E: I don’t know
>>> a
Working with Lists: For Loops and Conditionals

def copy_add_one(thelist):
"""Returns: copy with 1 added to every element
Precondition: thelist is a list of all numbers
(either floats or ints)"""
mycopy = [] # accumulator
for x in thelist:
x = x+1
A: [5, 4, 7]
mycopy.append(x)
B: [5, 4, 7, 5, 4, 7]
C: [6, 5, 8]
>>>return
a = [5, 4,mycopy
7]
D: Error
>>> b=copy_add_one(a)
E: I don’t know
>>> b
Working with Lists: For Loops and Conditionals

def add_one(thelist):
"""(Procedure) Adds 1 to every element in the list
Precondition: thelist is a list of all numbers
(either floats or ints)"""
size = len(thelist)
This Also
for k in range(size): WORKS!
thelist[k] = thelist[k]+1
# procedure; no return The list is
mutable!
Working with Lists: For Loops and Conditionals
Some List Functions/Methods

 len
 max
 min
 list.append()
 list.insert()
 list.remove()
 list.extend()
 list.pop()
 list.count()
 list.index()
 list.sort()

12/28/2024
Class Task - 1

a = [99,-43,22,-112,-55,0,-20,55,99,-22]

Split the list a into middle and store the elements in two
different lists as following: (use for loop)

b = [99,-43,22,-112,-55]
c = [0,-20,55,99,-22]

12/28/2024
Class Task - 2

a = [99,-43,22,-112,-55,0,-20,55,99,-22]

Find Minimum Element in the list a w/o using any


function/method.

12/28/2024

You might also like