COSC 2306
Data Programming
Python Basics
1
Lists and functions
def clearList(list):
list = []
mylist = [1,2,3]
clearList(mylist)
print(mylist)
def addItem(list, x):
list.append(x)
mylist = [1,2,3]
addItem(mylist,4)
print(mylist)
Fix me!
>[1, 2, 3, 4]
>[1, 2, 3]
def clearList(list):
list = []
return list
mylist = [1,2,3]
mylist = clearList(mylist)
print(mylist)
mylist.clear()
2
Lists and for loops
For loops offer a straightforward way to
traverse a list
fruits = ["apple", "orange", "banana", "cherry"]
for afruit in fruits: # by item
print(afruit)
fruits = ["apple", "orange", "banana", "cherry"]
for position in range(len(fruits)): # by index
print(fruits[position])
Lets capitalize all the
fruits in the list
3
fruits_upper = [item.upper() for item in fruits]
fruits_upper = []
for item in fruits:
fruits_upper.append(item.upper())
List Comprehension
Syntax: newList = [ expression(element) for element in
oldList if condition ]
Example: create a new list from an existing list with items contain “a”
# using for loop
fruits = ["apple", "banana", "cherry", "kiwi", "mango"]
newlist = []
for x in fruits:
if "a" in x:
newlist.append(x)
print(newlist)
>> ['apple', 'banana', 'mango]
# using list comprehension
fruits = ["apple", "banana", "cherry", "kiwi", "mango"]
4
newlist = [x for x in fruits if "a" in x]
print(newlist)
>> ['apple', 'banana', 'mango]
Nested List Comprehensions
matrix = [[0, 1, 2, 3, 4], [0, 1, 2, 3, 4], [0, 1, 2, 3, 4], [0, 1, 2, 3, 4],
[0, 1, 2, 3, 4]]
matrix = []
for i in range(5):
matrix.append([]) # Append an empty sublist inside the list
for j in range(5):
matrix[i].append(j)
print(matrix)
matrix = [[j for j in range(5)] for i in range(5)]
print(matrix)
5
Nested List Comprehensions
fruits = ["apple", "banana", "cherry", "kiwi", "mango"]
duplicate = [1,2,3]
newlist = [x for x in fruits for y in duplicate if "a" in x]
print(newlist)
['apple', 'apple', 'apple', 'banana', 'banana', 'banana', 'mango', 'mango',
'mango']
6
newlist = []
fruits = ["apple", "banana", "cherry", "kiwi", "mango"]
duplicate = [1,2,3]
for x in fruits:
for y in duplicate:
if “a in x:
newlist.append(x)
print(newlist)
String
7
Name
Purpose
lower()
Returns a string in all lowercase
upper()
Returns a string in all uppercase
center(w)
Returns a string centered in a field of size
𝑤
find(item)
Returns the index of the first occurrence of item
split(
s_char)
Splits a string into substrings at
s_char
count(item)
Returns the number of occurrences of item in the string
my_name = 'David'
my_name.upper() # 'DAVID'
my_name.center(10) # ' David '
my_name.find(v) # 2
my_name.split(v) # ['Da', 'id']
Tuple
8
Tuple is very similar to list, but immutable (similar to string)
my_tuple = (2,True,4.96)
print(my_tuple)
>>(2, True, 4.96)
print(len(my_tuple))
>>3
print(my_tuple[0])
>>2
print(my_tuple * 3)
>>(2, True, 4.96, 2, True, 4.96, 2, True, 4.96)
print(my_tuple[0:2])
>>(2, True)
Set
9
Name
Purpose
Example
union
Returns a new set with all elements from
both sets
set1.union(set2)
intersection
Returns a new set with only the elements
common to both sets
set1.intersection(set2)
difference
Returns a new set with all items from first
set not in second
set1.difference(set2)
issubset
Asks whether all elements of one set are in
the other
set1.issubset(set2)
add
Adds item to the set
set.add
(item)
remove
Removes item from the set
set.remove
(item)
pop
Removes an arbitrary element from the set
set.pop
()
clear
Removes all elements from the set
set.clear
()
Dictionaries
Mapping type associative collection
(key + value)
eng2sp = {}
eng2sp['one'] = 'uno'
eng2sp['two'] = 'dos'
eng2sp['three'] = 'tres'
#or
eng2sp = {'three': 'tres', 'one': 'uno', 'two': 'dos'}
print(eng2sp['two’])
>> dos
10
Dictionaries operations
inventory = {'apples': 430, 'bananas': 312, 'oranges': 525, 'pears': 217}
Operation
Example
Delete (by key)
del(inventory['pears'])
Modify
inventory['pears'] = 0
inventory['bananas']
= inventory['bananas'] + 200
11
Dictionaries operations
car = {
"brand": "Ford",
"model": "Mustang",
"year": 1964
}
x = car.get("price", 15000)
print(x)
12
15000
Dictionaries and aliasing
Dictionaries have the same aliasing problem
as lists (mutable)
opposites = {'up': 'down', 'right': 'wrong', 'true': 'false'}
alias = opposites
print(alias is opposites)
alias['right'] = 'left'
print(opposites['right'])
Use copy instead:
acopy = opposites.copy()
13
True
left
Namespace
1. Why?
assignment statement creates a symbolic name that you can use
to reference an object
hundreds or thousands of such names
need a good way to track all these names to avoid interference
2. How? namespace - collection of currently defined symbolic
names + object information that each name references
3. What? a namespace: a dictionary in which the keys are the
object names and the values are the objects themselves
4. Multiple namespaces and variable scope: the interpreter
determines the region where name has meaning (variable
scope)
5. LEGB rule (Python literature): searches from inside out
14
Namespace
1. Local: refer to x inside a function, the interpreter first
searches for the innermost scope (local to that function)
2. Enclosing: if x isn’t in the local scope but in a function that
resides inside another function, the interpreter searches in
the enclosing function’s scope
3. Global: if the above searches fail, the interpreter looks in the
global scope
4. Built-in: if it can’t find x anywhere else, the interpreter tries
the built-in scope.
15
LEGB rule
Namespace
x = 'global' #defines x in the global scope
def f():
x = 'enclosing' #defines x in the enclosing scope
def g():
x = 'local' #defines x in the scope local to g()
print(x)
g()
f()
>> local
16
Namespace
Python namespace dictionaries
- globals() returns global namespace dictionary
x = 'foo'
print(globals())
x is globals()['x’]
>>{'__name__': '__main__', '__doc__': None, '__package__': None,
'__loader__': <class '_frozen_importlib.BuiltinImporter'>, '__spec__': None,
'__annotations__': {}, '__builtins__': <module 'builtins' (built-in)>, 'x': 'foo'}
>>True
- local() returns local namespace dictionary
def f(x, y):
s = 'foo’
print(locals())
f(10, 0.5)
>>{'s': 'foo', 'y': 0.5, 'x': 10}
17
Namespace
The global declaration
18
x = 20
def f():
global x
x = 40
print(x)
f()
print(x)
>>40
>>40
#x is the x in the global namespace
#if x is not defined (remove x=20 above),
#it will create x as a global variable
not a good practice
-- similar purpose can be achieved by function return value
Manipulating files in Python
We must "open" a file with a name, which makes it a
Python object with a "file handle" for manipulation
fileHandle = open('myfile.txt')
Future reference to the file data is through fileHandle
And close the file in the end
20
Opening Files in Python
filehandle = open(filename,'r')
#Open a file called filename and use it for reading
filehandle = open(filename,'w')
#Open a file called filename and use it for writing
filehandle.close( )
#File use is complete
variable filehandle refers to the file content
21
Open file options
Mode
Read?
Write?
Overwrite?
Create
missing
file?
‘r
Yes
No
No
No
‘w
No
Yes
Yes
Yes
a’
No
Yes
No
Yes
22
COSC 2306
Data Programming
Python Basics
1
Where are these files?
On the hard drive (or flash drive), hierarchically
organized in folders/directories
Your program needs to specify the path:
absolute file path:
C:\Users\feng\Desktop\myfile.txt
/home/feng/myfile.txt
relative file path: ./feng/myfile.txt (relative to
execution location)
2
Reading files in Python
#reading the content in file as a string
fh= open(‘./myfile.txt’, ‘r’)
content = fh.read()
print(content)
fh.close()
line1
line2
line3
Note: The file content string will contain newline (\n) characters
3
Reading files in Python
#reading file as a list of strings each representing one line in
the file
fh= open(‘./myfile.txt', 'r')
lines = fh.readlines() #['line1\n', 'line2\n', 'line3\n…]
for aline in lines:
print(aline)
fh.close()
line1
line2
Line3
4
Reading files in Python
#reading one line at a time as a string
fh= open(./myfile.txt’, ‘r’)
line1 = fh.readline()
line2 = fh.readline()
line3 = fh.readline()
print(line1, line2, line3)
fh.close()
line1
line2
line3
5
Reading files in Python
#reading one line at a time in a loop
fh= open(‘./myfile.txt’,r)
line = fh.readline()
while line:
print(line)
line = fh.readline()
fh.close()
line1
line2
Line3
6
Reading files in Python
Pay attention to:
If the file doesn’t exist or is not in the path specified
python will throw an error
Content from the file is read as String
- use type conversion when needed
Remember to close the file once you’re done!
7
Writing to a file
To write data to a file you need to:
1. Open a file in writing mode:
fileHandle = open(newfile.txt', 'w')
2. Use the write method to send data to the file:
fileHandle.write(We won")
3. Close file when you’re done!
fileHandle.close()
Note:
Need to add your own newline characters (\n)
8
Writing to a file
To append data to a file you need to:
1. Open a file in append mode:
fileHandle = open(newfile.txt', a')
2. Use the write method to send data to the file:
fileHandle.write(We won")
3. Close file when you’re done!
fileHandle.close()
Note:
String data is simply appended to the end of the file
9
Writing to a file
Pay attention to:
If the file already exists, it will be rewritten/append, if it
doesn’t it will be created
The write method takes only strings as arguments, so
when needed, use type conversion
Remember to close the file when done!
10
Iterating over lines in a file
allines = filehandle.readlines()
for aline in allines:
print(aline)
mylist = aline.split()
Write a program that reads a filename and a string and
prints the number of occurrences of the string in each line
of the file
11
Iterating over lines in a file
filename = input ("What file?")
str = input("What string?")
fh = open(filename, 'r')
lines = fh.readlines()
for aline in lines:
count=0
mylist=aline.split()
for name in mylist:
if (name == string):
count = count+1
print("It occurs", count, "times")
fh.close()
12
13
COSC 2306
Data Programming
Python Basics
1
Programming
Algorithm: step-by-step (finite) list of instructions
for solving any instance of the problem, algorithms
are solutions
Programming: turn algorithm into a notation,
language that can be executed by a computer
Control structures and data types
- sequential execution is not sufficient
-> branches, loops
- basic data type is not sufficient
-> flexible data structure
Correctness, convenience, efficiency, portability, etc.
2
Programming Fundamentals
Flow Control
Branches
Loops and Iterations
Functions
Basic Data Types
Files, IO
3
if-else statement syntax
if <boolean_expression>:
<yes_statement>
else:
<no_statement>
5
Multiway if statement
if <boolean_expression>:
<first_statement>
elif <boolean_expression>:
<second_statement>
else:
<no_statement>
First true condition exits the block
6
Nested if statements
An if statement can include any command
including another if statement
Condition 1
Condition 2
Condition 3
Action 1
Action 2
Action 3
Action 4
if
if if
else
else else
7
Condition statement (true or false)
-- Equality and relational operators
8
Condition statement (true or false)
-- Logical operators
Opera tor
Description
Precedence
not
True when its operand is false
1
and
True when both operands are true
2
or
True when at least one of the operands is
true
3
9
Use parentheses to overwrite the precedence
Operator Precedence
10
COSC 2306
Data Programming
Python Basics
1
Whats the output?
x = -10
if x < 0:
print("The negative number ", x, " is not
valid here.")
print("This is always printed")
The negative number -10 is not valid here.
This is always printed
2
Whats the output?
x = 10
if x < 0:
print("The negative number ", x, " is not
valid here.")
print("This is always printed")
3
Python uses indentations to control logics
Whats the output?
x = -10
if x < 0:
print("The negative number ", x, " is not
valid here.")
else: print(x, " is a positive number")
else: print(x," is 0")
- Syntax error
4
Whats the output?
x = -10
if x < 0:
print(x, " is a negative number.")
elif x >0:
print(x, " is a positive number")
else:
print(x, " is 0")
-10 is a negative number.
5
Whats the output?
x = -10
if x < 0:
print(x, " is a negative number")
else:
if x > 0: print(x, " is a positive number")
else: print(x," is 0")
-10 is a negative number
-You can have an if/else statement under an else statement
6
Loops/Iteration
Loops allow us to specify a set of statements
that need to be repeated several times
We use computers to automate tasks - they are
really good at doing the same thing over and
over again
Python provides language features to support
iterations in our programs:
for loop
while loop
7
for and while
To repeat a block of code multiple times, we can
use loops (while or for):
A while loop will execute until some condition is
true
A for loop is better for known iterations and
counting
while x < 10:
#do something
for x in range(10):
#do something
Don’t forget to initialize and
update controlling variable
8
for Loop
The for statement allows us to iterate through
a sequence of values
for <var> in <sequence>:
<body>
The loop index variable var takes on each
successive value in the sequence, and the
statements in the body of the loop are executed
once for each value
9
Very Simple Example
for fruit in ["Apples", "Bananas",
"Grapes", "Oranges"]:
print ("We have " + fruit)
Output:
We have Apples
We have Bananas
We have Grapes
We have Oranges
10
Simple Counting Program
sum = 0
for number in [0, 1, 2, 3, 4, 5]:
sum = sum + number
print("The total is", sum)
sum = 0
for number in range(6):
sum = sum + number
print("The total is", sum)
11
Range
Range(n)
n is an integer
Iterates through 0, 1, n-1
Range(start, end, step)
Iterate from
start
to
end-1
with step length
step
Range(1, 7, 2): 1, 3, 5
Range() works like a list
12
For iteration
Iterator variable reset at the beginning of
each iteration
13
for number in range(5):
number = number + 2
print(number)
For iteration
Iterator variable reset at the beginning of
each iteration
14
2
3
4
5
6
for number in range(5):
number = number + 2
print(number)
Limitation of for Loops
The for loop is a
definite
loop, meaning that
the number of iterations is determined when the
loop starts
But the number may not always be known!
15
Example Problems
A program that asks a user to enter a sequence of
positive integers, with a “-1 entered to indicate the end
of the sequence (then the program computes and prints
the sum of the numbers)
This is a common pattern where the end of iterations is
indicated by a special value
A program that counts vowels in an input sentence?
A program that totals your grocery bill?
16
Example Problems
A program that accepts donations and stops when the
total reaches $1000?
In this pattern, condition to stop iterating is computed
dynamically
The program randomly picks a number between 1 and
100. The user guesses repeatedly, and program say
“hot”, “cold, or “bingo
A program that computes smallest P such that 3
P
is
greater than 1 million
17
while Loop
Syntax:
while <condition>:
<statements>
Here’s the flow of execution:
1. Evaluate the condition, yielding True or False
2. If condition is True, then execute the body of loop and go back to
step 1
3. If the condition is False, then exit the while statement and continue
execution at the next statement
18
Example of a while Loop
Sum the first 4 integers
sum = 0
while k < 5:
k = k + 1
sum = sum + k
print(sum)
sum = 0
for k in range(5):
sum = sum + k
print(sum)
k = 0
21
Countdown
for i in [5,4,3,2,1]:
print(i)
print("Blast off")
n=5
while n > 0:
print(n)
n = n-1
print("Blast off")
22
Sum a list of numbers
Write a program that asks a user to enter a sequence of
positive integers, with a “
-1”
entered to indicate the end of the
sequence. Then the program computes and prints the sum of
the numbers?
sum = 0
newnumber = int(input("Enter next number "))
while newnumber > 0:
sum = sum + newnumber
newnumber = int(input("Enter next number "))
print("The total is ", sum)
23
Example Problems
A program that accepts donations and stops when the total
reaches or exceeds $1000?
max = 1000.0
current_total =0.0
while current_total < max:
donation = float(input("Enter amount "))
current_total = current_total + donation
print ("Mission accomplished! Total raised $ ",
current_total)
24
Continue and Break in Loops
Sometimes we need to skip the current round of loop, or
terminate the whole loop.
continue: skip the current round, directly go to the next.
break: Terminate the loop.
for k in range(5):
if k == 3:
continue
print(k)
for k in range(5):
if k == 3:
break
print(k)
Continue and Break in Loops
Sometimes we need to skip the current round of loop, or
terminate the whole loop.
continue: skip the current round, directly go to the next.
break: Terminate the loop.
for k in range(5):
if k == 3:
continue
print(k)
[0,1,2,4]
for k in range(5):
if k == 3:
break
print(k)
[0,1,2]
Continue and Break in Loops
Continue and break only works for one-
layer of loop
27
for i in range(2):
for k in range(4):
if k == 2:
break
print(i,k)
Continue and Break in Loops
Continue and break only works for one-
layer of loop
28
for i in range(2):
for k in range(4):
if k == 2:
break
print(i,k)
0 0
0 1
1 0
1 1
The i-loop is not interrupted.
while Loop vs. for Loop
A for loop is less effort on the programmers side
If we know the number of iterations needed, then a for
loop is typically better
When we don’t know beforehand how many iterations,
then while loop is better
Any for loop problem can be solved with a while loop but
not the other way round
29
Functions: what and why
Functions are blocks of code grouped together
to perform a task
Advantages of functions:
Makes the code more readable
They are reusable
Black boxes
num = int(input())
result = num * num
import math
num = int(input())
result = math.pow(num,2)
31
Built-in functions
Many functions are already available in existing Python
-- modules (use import)
Example: the random module
random.random() returns a floating point number in the
range [0.0, 1.0)
random.randrange(x,y) returns an integer number in the
range [x, y)
Questions: how can you generate a floating point random
number between 0 and 100? And between 10 and 100?
import random
random.random() * 100
random.random() * 90 + 10
32
User defined functions
Its very easy to create new functions in Python
def newFunction( arguments ):
action 1
action 2
Example: let’s create a function to greet the user
def greeting(name):
print ("Hello! ", name, "!", sep="")
33
Fruitful or not?
The greeting function is unfruitful it
does not return a value
A fruitful function includes a return
statement:
def square(x):
y = x * x
return y
toSquare = 10
result = square(toSquare)
print("The result of", toSquare, "squared is", result)
> The result of 10 squared is 100
34
The return statement
Ends the function
Not always at the end of the function
def isItEven(x):
if x % 2 == 0:
return True
else:
return False
print(isItEven(10))
>True
35
Fruitful or not?
def square(x):
y = x * x
print(y)
toSquare = 10
result = square(toSquare)
print("The result of", toSquare, "squared is", result)
>100
>The result of 10 squared is None
*This is not a fruitful function since “None” was return
36
Local variables
Variables created inside a function can not be used
outside local variables
Arguments are also local variables
Global variables can be used, but it is not good practice
def badsquare(x):
y = x ** power
return y
power = 2
result = badsquare(10)
print(result)
>100
What happens if I try
to change power in
the function?
E.g., power = 3
>1000
37
Passing argument
def reassign(list):
list = [0, 1]
list = [0]
reassign(list)
print (list)
def append(list):
list.append(1)
list = [0]
append(list)
print (list)
>[0] >[0, 1]
38
Passing argument
Commonly, parameters are passed to a function
by reference or by value
Java is always pass by value, C++ has both
but not in Python
Reference: https://robertheaton.com/2014/02/09/pythons-
pass-by-object-reference-as-explained-by-philip-k-dick/
39
Pass-by-object-reference
The variable is not the object
a = []
[] is the empty list object
a is a variable that points to the empty list object
a itself is not the empty list object
40
Pass-by-reference
Pass-by-reference
the box (the variable) is passed directly into the function, and
its contents (the object represented by the variable) implicitly
come with it, the same location in memory
41
Pass-by-value
Pass-by-value
the function receives a copy of the argument objects, which is
stored in a new location in memory
42
Pass-by-object-reference
Pass-by-object-reference
The caller doesn’t care if you reassign the
functions box
Both the function and the caller refer to the same
object in memory, so append adds an extra item
to the list, we see this in the caller too
- the function receives a reference to the same object
in memory as used by the caller (similar as reference)
- it does not receive the box that the caller is storing
this object in
- the function provides its own box and creates a new
variable for itself (similar as pass-by-value)
43
Reference
Variable: hold reference to a piece of data (not
data itself)
Assignment statement: associate a name
(variable) with a piece of data (object)
44
theSum = 0
print(theSum)
>> 0
theSum = theSum + 1
print(theSum)
>> 1
theSum = True
print(theSum)
>> True
reassign may change data type
the same variable can refer to
many different types of data
Mutable vs Immutable
Every piece of data in Python is an object
Every variable reference to an object instance
When an object is initiated, it is assigned a
unique object id
Object type is defined at runtime and once set
can never change
Object state can be changed if it is mutable
Sum up: a mutable object can be changed after
it is created, and an immutable object cant
45
Mutable: flexible, less recreation; immutable: data consistency, efficiency
Why?
COSC 2306
Data Programming
Python Basics
1
Immutable types
Changes/reassign creates a new object
bool
tuple
string
float
int
frozenset
bytes
complex
2
Try this:
text = "Python"
text2 = text
print(id(text))
print(id(text2))
print(text is text2)
print()
text += " is awesome"
print(id(text))
print(id(text2))
print(text is text2)
print()
print(text)
print(text2)
3
Mutable vs. immutable in
functions
def updateNumber(n):
print(id(n))
n += 10
b = 5
print(id(b))
updateNumber(b)
print(b)
>2
>2 # pass-by-object-reference
>5 # immutable, from b = 5
and not from inside the def
def updateList(list1):
list1 += [10]
n = [5, 6]
print(id(n))
updateList(n)
print(n)
print(id(n))
>2
>[5, 6, 10]
>2
https://medium.com/@meghamohan/mutable-and-immutable-side-of-python-c2145cf72747
4
In-place
modification,
different from
list1 = list1 + [10],
which creates a
new object
Mutable vs. immutable in
functions
5
def updateNumber(n):
print(id(n))
n += 10
return n
b = 5
print(id(b))
b = updateNumber(b)
print(b)
print(id(b))
>2
>2 #pass-by-object-reference
>15 #return
>3 #immutable, new object
Helpful functions
I’m ready to
perform my
task!
Material
(arguments)
Return value
Local variables and
statements (tools)
Give all necessary
material!
May or may not
return something
6
The main function
Special function that is automatically invoked by
the operating system when the program is
executed
Although Python does not require one (unlike C++
or Java), it is good practice to have one
def greeting(name):
print("Hello ", name, "!", sep="")
def main():
n = input("What's your name? ")
greeting(n)
main()
7
Will this work?
def badsquare(x):
y = x ** power
return y
def main():
power = 2
result = badsquare(10)
print(result)
main()
*NameError: name “power” is not defined on line 2*
8
Try this
def badsquare(x, power):
y = x ** power
return y
def main():
power = 2
result = badsquare(10, power)
print(result)
main()
100
9
Functions with default values
In Python, functions can have default
arguments
def isDivisible(x, y = 2):
if x % y == 0:
return True
else:
return False
print(isDivisible(6))
print(isDivisible(6,4))
>True
>False
11
Python Built-in Data Types
Atomic data types:
int, float (arithmetic ops)
bool (true, false)
Ordered collection data types (indexed):
list ([], mutable, heterogenous)
string ("", immutable, characters)
tuple ((), immutable, heterogenous)
Unordered collection data types (hashing):
set ({}, mutable, heterogenous, immutable unique obj)
dictionary ({key:value}, mutable, heterogenous, unique
key pairs, key typically immutable)
12
Lists
A list is a sequential collection of Python data
values
They can hold any type (and mix them-heterogenous)
Similar to strings, but string can only hold characters
vocabulary = ["iteration", "selection", "control"]
mixedlist = ["hello", 2.0, 5*2, [10, 20]]
print(vocabulary)
print(mixedlist)
print(len(vocabulary))
print(len(mixedlist))
>['iteration', 'selection', 'control]
>['hello', 2.0, 10, [10, 20]]
>3
>4
13
Accessing lists
Lists can be accessed by indexing
Once an element is accessed, one can use it as a regular
variable of that type
numbers = [17, 123, 87, 34, 66, 8398, 44]
print(numbers[2])
print(numbers[-2])
print(numbers[len(numbers) - 1])
alist = [3, 67, "cat", [56, 57, "dog"], [ ], 3.14, False]
print(alist[2][0])
print(alist[2].upper())
print(alist[2])
>87
>8398
>44
>c
>CAT
>cat
14
print(numbers[len(numbers)])
IndexError: list index out of range
Other list operations
Name
Purpose
Example
Membership (in)
Test if an item is in a list
fruit = ["apple", "orange",
"banana", "cherry"]
print("apple" in fruit)
>True
Concatenation (+)
Merge two lists
print([1, 2] + [3, 4])
>[1, 2, 3, 4]
Repetition (*)
Repeat a list
print([0] * 4)
>[0, 0, 0, 0]
Slicing ([:])
Access a range of items
alist
= ['a', 'b', 'c', 'd']
print(
alist[1:3])
print(
alist[:4])
>['b', 'c']
>['a', 'b', 'c', 'd']
Deletion (del)
Remove element(s)
alist
= ['a', 'b', 'c', 'd']
del
alist[1] #['a', 'c', 'd']
del
alist
[:1] #['b', 'c', 'd']
15
list operation example
16
alist = [1,2]
print(id(alist))
blist = [3,4]
print(id(blist))
clist = (alist + blist)
print(clist)
print(id(clist))
2
3
[1,2,3,4]
4
Lists are mutable
fruit = ["banana", "apple", "cherry"]
print(fruit)
fruit[0] = "pear"
fruit[-1] = "orange"
print(fruit)
astring = "Hello"
astring[0] = "W"
print(astring)
You can use id(fruit) to verify that the
identifier of fruit stayed the same
TypeError: 'str' object does not support item assignment
>['banana', 'apple', 'cherry’]
>['pear', 'apple', 'orange']
17
Aliasing vs. cloning
a = [81, 82, 83]
b = a[:]
print(a is b)
print(a == b)
a[1] = 0
print(a)
print(b)
a = [81, 82, 83]
b = a
print(a is b)
print(a == b)
a[1] = 0
print(a)
print(b)
>True
>True
>[81, 0, 83]
>[81, 0, 83]
>False
>True
>[81, 0, 83]
>[81, 82, 83]
18
More list methods
mylist = mylist.sort()?
19