0% found this document useful (0 votes)
13 views40 pages

05 Lists Advanced

Lists

Uploaded by

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

05 Lists Advanced

Lists

Uploaded by

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

Lists Advanced

SoftUni Team
Technical Trainers
Software University
https://softuni.bg
Table of Contents

1. List Comprehensions
2. List Methods
3. Advanced Functions
4. Additional List Manipulations
5. The set() function

2
Have a Question?

sli.do
#fund-python
3
List Comprehensions
What is Comprehension?
▪ Comprehensions provide us with a short way to
construct new sequences
▪ They allow sequences to be built from
other sequences
▪ They require less memory
▪ They have shorter syntax and better performance

5
Structure
▪ A list comprehension consists of the following parts:
▪ An input sequence
▪ A variable representing members of the input sequence
▪ An optional predicate expression
▪ An output expression producing elements in the output list

6
List Comprehensions
▪ Creating a list using the range function
Output Expression

x = [num for num in range(5)]


# [0, 1, 2, 3, 4] Variable

▪ Getting the square values of numbers in a list


nums = [1, 2, 3, 4] Input Sequence
squares = [x**2 for x in nums]
# [1, 4, 9, 16]

7
List Comprehensions (2)
▪ Using if statement in a list comprehension
nums = [1, 2, 3, 4, 5, 6]
evens = [num for num in nums if num % 2 == 0]
# [2, 4, 6]
Optional Parameter
▪ Using if-else statement in a list comprehension
nums = [1, 2, 3, 4, 5, 6]
filtered = [True if x % 2 == 0 else False for x in nums]
# [False, True, False, True, False, True]

8
Problem: No Vowels
▪ Write a program that receives a text and removes all the
vowels from it
▪ Print the new text string after removing the vowels
▪ The vowels that should be considered are 'a', 'o', 'u', 'e', 'i'
ILovePython LvPythn

9
Solution: No Vowels

text = input()
vowels = ['a', 'u', 'e', 'i', 'o', 'A', 'U', 'E', 'I', 'O']
no_vowels = ''.join([x for x in text if x not in vowels])
print(no_vowels)

10
List Methods
Adding Elements
▪ Using the append() method
Add single element
my_list = [1, 2, 3] at the end
my_list.append(4) # [1, 2, 3, 4]

▪ Using the extend() method


Add multiple
my_list = [1, 2, 3] elements at the end
my_list.extend([4, 5]) # [1, 2, 3, 4, 5]

▪ Using the insert() method


Add single element
my_list = [1, 2, 3] at a specific index
my_list.insert(1, 4) # [1, 4, 2, 3]
12
Removing Elements
▪ Using the clear() method
my_list = [1, 2, 3]
Removes all elements
my_list.clear() # []

▪ Using the pop() method


Removes element by
my_list = [1, 2, 3] index and returns it
number = my_list.pop(0) # [2, 3]; number -> 1

▪ Using the remove() method


Removes by value
my_list = [1, 2, 3] (first occurrence)
my_list.remove(1) # [2, 3]
13
Problem: Trains
▪ You will receive how many wagons the train has
▪ Until you receive "End", you will get some of the commands:
▪ add {people} -> adds the people in the last wagon
▪ insert {index} {people} -> adds the people at the given wagon
▪ leave {index} {people} -> removes the people from the wagon
3
add 20
insert 0 15 [10, 0, 20]
leave 0 5
End
14
Solution: Trains
train_length = int(input())
train = [0] * train_length
Generate list with
same values
command = input()
while command != "End":
tokens = command.split(" ")
key_word = tokens[0]
if key_word == "add":
# Implement
# Add the other cases
command = input()
print(train)
15
Problem: Todo List
▪ You will be receiving to-do notes until you get the command "End"
▪ The notes will be in the format: "{priority}-{note}"
▪ Return the list of to-do notes sorted by priority (ascending)
▪ Hint: use the pop() and the insert() methods
2-Walk the dog
1-Drink coffee
6-Dinner ['Drink coffee', 'Walk the dog', 'Work', 'Dinner']
5-Work
End
16
Solution: Todo List
notes = [0] * 10
Creating list with 10 zeros
while True:
command = input()
if command == "End":
break
tokens = command.split("-")
priority = int(tokens[0]) - 1
note = tokens[1]
notes.pop(priority)
notes.insert(priority, note)
# Add only the elements that are not 0
17
More Useful Methods
▪ Using the count() method
Finds all occurrences in
my_list = [1, 2, 3, 2, 2] a list
my_list.count(2) # 3

▪ Using the index() method


Finds the index of the
my_list = [1, 2, 3, 2, 2] first occurrence
last = my_list.index(2) # 1

▪ Using the reverse() method


Reverses the elements
my_list = [1, 2, 3]
my_list.reverse() # [3, 2, 1]
18
Problem: Palindrome Strings
▪ You will receive words separated by a single space
and a palindrome
▪ Print a list containing all the palindromes
▪ Print the number of occurrences of the palindrome in the
format: "Found palindrome {number} times"

wow father mom wow shirt stats ['wow', 'mom', 'wow', 'stats']
wow Found palindrome 2 times

19
Solution: Palindrome Strings

strings = input().split(" ")


searched_palindrome = input() Reversed returns iterator
object, so we join
palindromes = []
it to a string
for word in strings:
if word == "".join(reversed(word)):
palindromes.append(word)
print(f"{palindromes}")
print(f"Found palindrome
{palindromes.count(searched_palindrome)} times")

20
Advanced Functions
Using Lambda Operators
sorted() Function
▪ Sorts the elements of a list in ascending order
numbers_list = [6, 2, 1, 4, 3, 5]
sorted_numbers = sorted(numbers_list)
# [1, 2, 3, 4, 5, 6]

▪ Sorts the elements of a list in descending order


numbers_list = [6, 2, 1, 4, 3, 5]
sorted_numbers = sorted(numbers_list, key=lambda x: -x)
# [6, 5, 4, 3, 2, 1]

22
Problem: Sorting Names
▪ Write a program that reads a single string with names
separated by comma and space ", "
▪ Sort the names by their length in descending order
▪ If 2 or more names have the same length, sort them in
ascending order (alphabetically)
▪ Print the resulting list Ali, Marry, Kim, Teddy, Monika, John

["Monika", "Marry", "Teddy", "John", "Ali", "Kim"]

23
map() Function
▪ Use it to convert list of strings to list of integers
Returns int(x) for each
element x in the list
strings_list = ["1", "2", "3", "4"]
numbers_list = list(map(int, strings_list)) # [1, 2, 3, 4]

▪ It applies function to every item of an iterable


numbers_list = [1, 2, 3, 4]
doubled_list = list(map(lambda x: x*2, numbers_list))
# [2, 4, 6, 8]

▪ It returns an iterator object, so you need to convert it into a list


24
filter() Function
▪ Use it to filter elements that fulfill a given condition
Filter all the even
numbers_list = [1, 2, 3, 4, 5, 6] numbers
even_numbers = list(filter(lambda x: x % 2 == 0, numbers_list))
# [2, 4, 6]

▪ The lambda should return either True or False


▪ It returns an iterator object, so you need to convert it into a list

25
Problem: Even Numbers
▪ Write a program that reads a single string with numbers
separated by comma and space ", "
▪ Print the indices of all even numbers

3, 2, 1, 5, 8 [1, 4]

2, 4, 6, 9, 10 [0, 1, 2, 4]

26
Solution: Even Numbers

# Convert the list of strings into a list of numbers


number_list = list(map(int, input().split(", ")))
# Find all the even numbers' indices
found_indices_or_no = map(
lambda x: x if number_list[x] % 2 == 0 else 'no',
range(len(number_list)))
# Filter only the indices
even_indices = list(filter(lambda a: a != 'no', found_indices_or_no))
print(even_indices)

27
Problem: The Office
▪ Read the problem description here

1 2 3 4 2 1
Score 2/6. Employees are not happy!
3

2 3 2 1 3 3
Score: 3/6. Employees are happy!
4

28
Solution: The Office

employeеs = input().split(" ")


happiness_factor = int(input())
employees = # Use map to multiply each element with the factor
filtered = # Use filter to get all the numbers >= than the average
if len(filtered) >= len(employees) / 2:
print(f"Score: {len(filtered)}/{len(employees)}. Employees are
happy!")
else:
print(f"Score: {len(filtered)}/{len(employees)}. Employees are
not happy!")

29
Additional List Manipulations
Swapping List Elements
▪ You can use the following syntax to swap two or more
list elements
nums = [1, 2, 3]
nums[0], nums[1], nums[2] = nums[2], nums[0], nums[1]
# 1 swaps with 3
# 2 swaps with 1
# 3 swaps with 2

▪ The first element on the left swaps with the first on the
right etc.
31
Concatenating Lists
▪ You can use the "+" operator to join two lists
nums_list_1 = [1, 2, 3]
nums_list_2 = [4, 5, 6]
final_list = nums_list_1 + nums_list_2
print(final_list) # [1, 2, 3, 4, 5, 6]

▪ Always the second list is added at the end of the first

32
The Set Function
▪ You can use the set() function to extract only the unique
elements from a list
numbers = [1, 2, 2, 3, 1, 4, 5, 4]
unique_numbers = list(set(numbers)) # [1, 2, 3, 4, 5]

▪ The set() function returns a set with the unique values


▪ You will learn more about sets in the advanced
python module

33
Live Exercises
Summary

▪▪ We
… learned:
▪ ▪…Some additional methods that can be
▪ …used with lists
▪ Some basic lambda functionality
▪ How to swap list elements

35
Questions?
SoftUni Diamond Partners
Educational Partners

38
Trainings @ Software University (SoftUni)
▪ Software University – High-Quality Education,
Profession and Job for Software Developers
▪ softuni.bg, softuni.org
▪ Software University Foundation
▪ softuni.foundation
▪ Software University @ Facebook
▪ facebook.com/SoftwareUniversity
▪ Software University Forums
▪ forum.softuni.bg
39
License

▪ This course (slides, examples, demos, exercises, homework,


documents, videos and other assets) is copyrighted content
▪ Unauthorized copy, reproduction or use is illegal
▪ © SoftUni – https://softuni.org
▪ © Software University – https://softuni.bg

40

You might also like