Created for.
A sequence in Python is a container, storing ordered collection of objects.
length, indexing, slicing, concatenation, repetition, membership test, min, max, count, index
.
# list:
fruits = ["apple", "banana", "strawberry", "banana", "orange"]
# tupple:
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]
]
var_name = 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']
### create empty tuple:
empty = ()
print( empty )
# ()
### create tuple with one element - note the trailing comma!
t = (99,)
print(t)
# (99,)
### create tuple of 3 elements:
point3d = (4, 0, 3)
print(point3d)
# (4, 0, 3)
var_name = tupple_name[index]
### retrieve tuple items
address = ('Bulgaria', 'Sofia', 'Nezabravka str', 14)
country = address[0]
town = address[1]
street = address[2]
street_num = address[3]
print(country, town, street, street_num)
# Bulgaria Sofia Nezabravka str 14
### change a tuple item:
address[0] = "France"
# TypeError: 'tuple' object does not support item assignment
### 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 181
for
loops.
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(9, -1, 1)
# incorrect sequence formulae, will return empty sequence
### iterate from 0 up to 10, step = 1 (default)
for i in range(0,10):
print(i, end=" ")
# 0 1 2 3 4 5 6 7 8 9
### iterate from 10 up to -1, step = -1
for i in range(10,-1, -1):
print(i, end=" ")
# 10 9 8 7 6 5 4 3 2 1 0
### iterate from 2 up to 10, step = 2
for i in range(2, 10, 2):
print(i, end=" ")
# 2 4 6 8
### iterate from -10 up to 0, step = 2
for i in range(-10, 0, 2):
print(i, end=" ")
# -10 - 8 - 6 - 4 - 2
### iterate from 0 (Default) 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, "Decemeber", 2017)
date2 = (10, "Mart", 1999)
conc_date = date1 + date2
print(conc_date)
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
sliced = sequence[start:end:step]
:
) is required!
>>> str = "abcdef"
>>> str[:]
'abcdef'
>>> str[2:4]
'cd'
>>> str[]
SyntaxError: invalid syntax
# get items from start through end-1
s[start:end]
# get items from start through the rest of the array
s[start:]
# get items from the beginning through end-1
s[:end]
# get items from begining through the end
# i.e. copy of the whole array
s[:]
>>> str = "abcdef"
>>> str[0:3]
'abc'
>>> str[:3]
'abc'
>>> str[2:3]
'c'
>>> str[3:]
'def'
>>> str[-1:-7:-1]
'fedcba'
for item in sequence:
# do something with item
### loop on list items:
for item in [1,2,3]:
print(item)
### loop on tuple items:
for item in (10, "December", 1985):
print(item)
### loop on string items:
for item in "byron":
print(item)
### loop on range items:
for item in range(1,3):
print(item)
list()
list()
function we can create a list from any sequence:
### list from tupple:
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']
fruits = ["apple", "orange", "strawberry"]
### Delete a list item by index
del fruits[1]
print(fruits)
# ['apple', 'strawberry']
### Create list of fruits:
fruits = ["apple", "banana", "strawberry"]
### Appends item 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']
### Retrieve the item at the end and remove it from the list:
item = fruits.pop()
print(item, fruits)
# plum ['apple', 'banana', 'NEW', 'strawberry']
### Retrieve the item at the index given and remove it from the list:
item = fruits.pop(2)
print(item, fruits)
# NEW ['apple', 'banana', 'strawberry']
### Remove the first item from a list by 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']
### 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
### create list_of_tuples:
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()
tuple()
function we can create a tuple from any sequence:
### tuple from list:
fruits = ["apple", "banana", "strawberry", "banana", "orange"]
fruits_tuple = tuple(fruits)
print(fruits_tuple)
# ('apple', 'banana', 'strawberry', 'banana', 'orange'
### tuple from range:
digits = range(0, 10)
digits_tuple = tuple(digits)
print(digits_tuple)
# (0, 1, 2, 3, 4, 5, 6, 7, 8, 9)
### tuple from string:
user_name = "ada byron"
user_name_tuple = tuple(user_name)
print(user_name_tuple)
# ('a', 'd', 'a', ' ', 'b', 'y', 'r', 'o', 'n')
first_names
with items "ivan", "maria", "petar"sur_names
with items "ivanov", "popova", "petrov"names
, which will holds the items from the two list above as given:
print(names)
# ['ivan', 'maria', 'petar', 'ivanov', 'popova', 'petrov']
first_names = ["ivan", "maria", "petar"]
sur_names = ["ivanov", "popova", "petrov"]
names = first_names + sur_names
print(names)
first_names
and sur_names
as in previous task.first_names
and sur_names
create a third list:names
which will hold the items from the two list with next order:
print(names)
# ['ivan', 'ivanov', 'maria', 'popova', 'petar', 'petrov']
first_names = ["ivan", "maria", "petar"]
sur_names = ["ivanov", "popova", "petrov"]
# names will store the third list. In the beginning it's empty:
names = []
# make the third list:
for i in range(len(first_names)):
names.append(first_names[i])
names.append(sur_names[i])
print(names)
first_names = ["ivan", "maria", "petar"]
sur_names = ["ivanov", "popova", "petrov"]
# names will store the third list. In the beginning it's empty:
names = []
# make the third list:
for i in range(len(first_names)):
names = names + [first_names[i], sur_names[i]]
print(names)
111100
# in the beginning the sum is 0:
sum = 0
# add each number to the current sum:
for i in range(1000, 1201):
# you can skip next line, if you add step 2 in range
if i % 2 == 0:
sum += i
print(sum)
# in the beginning the sum is 0:
sum = 0
first_num = 1000
last_num = 1200
# add each number to the current sum:
num = first_num
while num <= last_num:
if num % 2 == 0:
sum += num
num += 1
print(sum)
Given are next list of words:
words = ["dog", "talent", "loop", "aria", "tent", "choice"]
Write a program which will find and output all of the words which starts and ends with same letter
Words which starts and end with same letter are:
talent
aria
tent
words = ["dog", "talent", "loop", "aria", "tent", "choice"]
print("Words which starts and end with same letter are:")
for word in words:
# if first letter is equal to last letter:
if word[0] == word[-1]:
print(word)
How many names are you going to enter? 3
Enter a name, please: Maria
Enter a name, please: Ivan
Enter a name, please: Stoyan
******************************
The names you've entered are:
Maria
Ivan
Stoyan
names_count = int(input("How many names are you going to enter? "))
# names will be stored in next list:
names = []
# get and save to names the user input:
for i in range(names_count):
name = input("Enter a name, please: ")
# append user input to names list:
names.append(name)
# now print what user have entered:
print("*" * 30)
print("The names you've entered are:")
for name in names:
print(name)
Given are next list of distances from Sofia:
distances_from_sofia = [
('Bansko', 97),
('Brussels', 1701),
('Alexandria', 1403),
('Nice', 1307),
('Szeged', 469),
('Dublin', 2479),
('Palermo', 987),
('Oslo', 2098),
('Moscow', 1779),
('Madrid', 2259),
('London', 2019)
]
Write a program, which will outputs only the distances from Sofia which are bellow 1500km
Distances bellow 1500 km from Sofia are:
Bansko - 97
Alexandria - 1403
Nice - 1307
Szeged - 469
Palermo - 987
distances_from_sofia = [
('Bansko', 97),
('Brussels', 1701),
('Alexandria', 1403),
('Nice', 1307),
('Szeged', 469),
('Dublin', 2479),
('Palermo', 987),
('Oslo', 2098),
('Moscow', 1779),
('Madrid', 2259),
('London', 2019)
]
# variable to store the filtered list of distance tuples:
selected_distances = []
# filter each distance tuple:
for item in distances_from_sofia:
# each item is a tuple, and we check its second value:
if(item[1] < 1500):
selected_distances.append(item)
# print the filtered list of distance tuples:
print("Distances bellow 1500 km from Sofia are:")
for item in selected_distances:
print("{} - {}".format(item[0], item[1]))
These slides are based on.
customised version of .
framework.