?print-pdf
' Created for.
length, indexing, slicing, concatenation,
repetition, membership test, min, max, count, index
.
# list:
fruits = ["apple", "banana", "strawberry", "banana", "orange"]
# tuple:
point3d = (4, 0, 3)
# range:
digits = range(0,10)
# string:
user_name="ada byron"
### create empty list:
empty_list = []
### create list of numbers:
users = [1,2,3,4,5]
### create list of lists
matrix = [
[1,2,3],
[4,5,6],
[7,8,9]
]
item = list_name[index]
### create list:
fruits = ["apple", "banana", "strawberry", "banana", "orange"]
### retrieve the first item in the list:
item1 = fruits[0]
# apple
### retrieve third item in the list.
item3 = fruits[2]
# strawberry
# retrieve last item in the list:
itemN = fruits[-1]
# orange
We will discuss more indexing operation in Common Sequence Operations.
list_name[index] = value
### create list:
fruits = ["apple", "banana", "strawberry"]
### Change second list item
fruits[1] = "plum"
print( fruits )
# ['apple', 'plum', 'strawberry']
### Change last list item
fruits[-1] = "orange"
print( fruits )
# ['apple', 'plum', 'orange']
(1,)
### create empty tuple:
t = ()
print(type(t))
#<class 'tuple'>
### create tuple with one element - note the trailing comma!
# if you write t = (99), it will be an integer, not tuple
t = (99,)
print(type(t))
# <class 'tuple'>
n = (99)
print(type(n))
<class 'int'>
### create tuple of 3 elements:
point3d = (4, 0, 3)
print(point3d)
# (4, 0, 3)
item = tuple_name[index]
# create a tuple
address = ('Bulgaria', 'Sofia', 'Nezabravka str', 14)
# retrieve tuple items
country = address[0]
town = address[1]
street = address[2]
street_num = address[3]
print(country, town, street, street_num)
# Bulgaria Sofia Nezabravka str 14
### create tuple with 3 elements:
ada_birth_date = (10, "December", 1815)
# retrieve tuple elements:
ada_birth_day = ada_birth_date[0]
ada_birth_month = ada_birth_date[1]
ada_birth_year = ada_birth_date[2]
print("Ada is born on {} {} in {}".format(ada_birth_month, ada_birth_day, ada_birth_year))
# Ada is born on December 10 in 1815
### change a tuple item:
address[0] = "France"
# TypeError: 'tuple' object does not support item assignment
t = ([1,2,3],)
# change third element in the list inside a tuple:
t[0][2] = 100
print(t)
#([1, 2, 100],)
list()
and tuple()
built-in functions.
address = ('Bulgaria', 'Sofia', 'Nezabravka str', 14)
# convert value in address to list
address = list(address)
address[3] = 25
print(address)
# ['Bulgaria', 'Sofia', 'Nezabravka str', 25]
range(stop)
range(start, stop[, step])
range(0,10)
# generates the sequence: [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
range(10)
# same as above
range(2, 10, 2)
# generates the sequence: [2, 4, 6, 8]
range(9, -1, -1)
# generates the sequence: [9, 8, 7, 6, 5, 4, 3, 2, 1, 0]
range(-3, 4)
# generates the sequence: [-3, -2, -1, 0, 1, 2, 3]
range(9, -1, 1)
# incorrect sequence formulae, will return empty sequence
r = range(0, 10, 2)
print(r)
# range(0, 10, 2)
list()
or tuple()
function:
r = range(0, 10, 2)
print(list(r))
# [0, 2, 4, 6, 8]
### iterate from 0 up to 10, step = 1 (default)
for i in range(10):
print(i, end=" ")
# 0 1 2 3 4 5 6 7 8 9
Next operation can be used on all sequence types, with the exception that range() objects can not be concatenated or repeated (but the sequences they produced can).
Operation | Operator |
---|---|
Concatenation | + |
Repetition | * |
Membership Testing | in (not in) |
Indexing | [i] |
Slicing | [i:j] |
### Let's have two lists:
fruits = ["apple", "banana", "strawberry"]
numbers = [1,2,3]
### We can concatenate them:
concat_list = fruits + numbers
print(concat_list)
# ['apple', 'banana', 'strawberry', 1, 2, 3]
num_list = [1,2,3]
alpha_list = ["a", "b", "c"]
conc_list = num_list + alpha_list
print(conc_list)
# [1, 2, 3, 'a', 'b', 'c']
Note, that the result is a list!
date1 = (31, "December", 2017)
date2 = (10, "Mart", 1999)
conc_date = date1 + date2
print(conc_date)
# (31, 'December', 2017, 10, 'Mart', 1999)
Note, that the result is a tuple!
### Let's have a list:
numbers = [1, 2, 3]
### Repetition
rep_list = numbers * 3
print(rep_list)
# [1, 2, 3, 1, 2, 3, 1, 2, 3]
num_list = [1, 2, 3]
alpha_list = ["a", "b", "c"]
print(num_list*3)
print(alpha_list*3)
# [1, 2, 3, 1, 2, 3, 1, 2, 3]
# ['a', 'b', 'c', 'a', 'b', 'c', 'a', 'b', 'c']
### Let's have two list:
fruits = ["apple", "banana", "strawberry"]
numbers = [1, 2, 3]
### Membership Testing (in):
print("banana" in fruits)
# True
print("banana" in numbers)
# False
### Membership Testing (not in):
print("banana" not in fruits)
# False
print("banana" not in numbers)
# True
# Let's have a range:
r = range(0,10)
print(3 in r)
# True
print(21 in r)
# False
### create list of numbers:
numbers = [1,2,3,4,5]
### index from start to end:
print(numbers[0],numbers[1],numbers[2],numbers[3],numbers[4])
# 1 2 3 4 5
### create list of numbers:
numbers = [1,2,3,4,5]
### index from end to start:
print(numbers[-1],numbers[-2],numbers[-3],numbers[-4],numbers[-5])
# 5 4 3 2 1
-1
index, not by len()-1
fruits = ["apple", "banana", "strawberry"]
# the pythonic way to print last element
print(fruits[-1])
# "strawberry"
# not pythonic (though it works):
print(fruits[len(fruits)-1])
# "strawberry"
sliced = sequence[start:end:step]
start
: The starting index of the slice (inclusive).stop
: The ending index of the slice (exclusive).step
: The step size or increment. If omitted, it defaults to 1.
a[start:end] # get items with indexes from start through end-1
a[start:] # get items with indexes from start through the rest of the array
a[:end] # get items with indexes from the beginning through end-1
a[:] # get all items (a copy of the whole sequence)
# Slicing a String
greeting = "Hello, World!"
print(greeting[1:5]) # 'ello'
# Slicing a List
numbers = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
print(numbers[2:5]) # [2, 3, 4]
# Slicing with Step
print(numbers[1:9:2]) # [1, 3, 5, 7]
# Get first 3 elements
print(numbers[:3]) # [0, 1, 2]
# Get last 3 elements
print(numbers[:-4:-1]) # [9, 8, 7]
# Reverse Slicing
print(numbers[::-1]) # [9, 8, 7, 6, 5, 4, 3, 2, 1, 0]
# Slice all elements (copy list):
numbers_copy = numbers[:]
print(numbers_copy) # [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
list()
list()
function we can create a list from any sequence:
### empty list:
l = list() # equivalent to l = []
### list from tuple:
point3d = (4, 0, 3)
point3d_list = list(point3d)
print(point3d_list)
# [4, 0, 3]
### list from range:
digits = range(0, 10)
digits_list = list(digits)
print(digits_list)
# [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
### list from string:
user_name = "ada byron"
user_name_list = list(user_name)
print(user_name_list)
# ['a', 'd', 'a', ' ', 'b', 'y', 'r', 'o', 'n']
### Create list of fruits:
fruits = ["apple", "banana", "strawberry"]
### Insert item at the end of the list:
fruits.append("plum")
print(fruits)
# ['apple', 'banana', 'strawberry', 'plum']
### Insert item in specified position (by the index given as first parameter)
fruits.insert(2, "NEW")
print(fruits)
# ['apple', 'banana', 'NEW', 'strawberry', 'plum']
### Remove last list item and retrieve it:
item = fruits.pop()
print(item, fruits)
# plum ['apple', 'banana', 'NEW', 'strawberry']
### Remove item at specified position and retrieve it::
item = fruits.pop(2)
print(item, fruits)
# NEW ['apple', 'banana', 'strawberry']
### Remove the first item from a list matching the given value:
fruits.remove("banana")
print(fruits)
# ['apple', 'strawberry']
### Reverse the items of a list in place:
fruits.reverse()
print(fruits)
# ['strawberry', 'banana', 'apple']
### Sort list "in-place". I.e. the list itself will be sorted, will not create a copy:
l = [1,3,4,2]
l.sort()
print(l)
# [1, 2, 3, 4]
For more - check the: python.org tutorial
### create list of lists:
matrix = [
[1,2,3],
[4,5,6],
[7,8,9],
]
### retrieve the first element from the first list:
print(matrix[0][0] )
# 1
### retrieve the last element from the first list:
print(matrix[0][-1])
# 3
### retrieve the first element from the last list:
print(matrix[-1][0])
# 7
### retrieve the last element from the last list:
print(matrix[-1][-1])
# 9
m = [
[1,2,3],
[4,5,6],
[7,8,9],
]
# trying to slice the second column ([2,5,8]):
print(m[:,1])
# TypeError: list indices must be integers or slices, not tuple
pip install numpy
import numpy
# lets create a python list
m = [
[1,2,3],
[4,5,6],
[7,8,9],
]
# create a numpy array from that list:
arr = numpy.array(m)
# now we can easily use numpy's multi-dim slicing:
print(arr[:,1])
#[2 5 8]
print(type(arr[:,1]))
[2 5 8]
<class 'numpy.ndarray'>
### create list_of_tuples representing a point 3D coordinates:
points = [
(1,2),
(3,4),
(5,6)
]
### retrieve the first element from the first tuple:
print(points[0][0])
# 1
### retrieve the last element from the first tuple:
print(points[0][-1])
# 2
### retrieve the first element from the last tuple:
print(points[-1][0])
# 5
### retrieve the last element from the last tuple:
print(points[-1][-1])
# 6
# Tuple of lists: product names and their quantities
products = (
['Shirt', 'Pants'],
[20, 35]
)
# Printing product 1 details
print(f"Product: {products[0][0]}, Quantity: {products[1][0]}")
# Product: Shirt, Quantity: 20
### change the quantity for product 1:
users[0][2] = 100
print(users[0])
# ['Ivan', 'Ivanov', 100]
### try to change the tuple itself:
users[0] = ["Petyr", "Petrov", 45]
# TypeError: 'tuple' object does not support item assignment
# Original list
original_list = [1, 2, 3]
# Assigning reference of the original list to new_list
new_list = original_list
# Modifying new_list also affects original_list
new_list[0] = 100
print(original_list) # Output: [100, 2, 3]
print(new_list) # Output: [100, 2, 3]
new_list = original_list
does not create a new list. Instead, new_list references the same list object as original_list. Both 'new_list
' and 'original_list
' refer to the exact same list in memory.
original_list = [1,2,3]
new_list = original_list # new_list refers to the same object as original_list
# Get the memory address (id) of both variables
print(f"Memory address of original_list: {id(original_list)}")
print(f"Memory address of new_list: {id(new_list)}")
# Check if both variables refer to the same object in memory
print( original_list is new_list)
# Original list with nested list (mutable object inside)
original_list = [1, 2, [3, 4]]
# Create a shallow copy using slicing
shallow_copy = original_list[:]
# Modify the inner list in the shallow copy
shallow_copy[2][0] = 99
# Output the lists
print(f"Original list: {original_list}") # [1, 2, [99, 4]]
print(f"Shallow copy: {shallow_copy}") # [1, 2, [99, 4]]
# Check if both lists are the same object
print(original_list is shallow_copy) # False, because the outer lists are different
print(original_list[2] is shallow_copy[2]) # True, because the inner list is shared
new_list = original_list[:]
new_list = original_list.copy()
import copy
new_object = copy.copy(original_object)
copy.deepcopy(l)
method from the copy
module
import copy
# Original list with nested list (mutable object inside)
original_list = [1, 2, [3, 4]]
# Create a deep copy
deep_copy = copy.deepcopy(original_list)
# Modify the inner list in the deep copy
deep_copy[2][0] = 99
# Output the lists
print(f"Original list: {original_list}") # [1, 2, [3, 4]]
print(f"Deep copy: {deep_copy}") # [1, 2, [99, 4]]
# Check if both lists are the same object
print(original_list is deep_copy) # False, because they are different objects
print(original_list[2] is deep_copy[2]) # False, because the inner lists are different objects
These slides are based on.
customised version of .
framework.