SlideShare a Scribd company logo
1 of 55
6. List
1ARULKUMAR V Ap/CSE SECE
Opening Problem
Read one hundred numbers, compute their
average, and find out how many numbers are
above the average.
2ARULKUMAR V Ap/CSE SECE
Solution
3
DataAnalysis Run
ARULKUMAR V Ap/CSE SECE
Objectives
• To describe why lists are useful in programming (§10.1).
• To create lists (§10.2.1).
• To invoke list’s append, insert, extend, remove, pop, index, count, sort, reverse methods
(§10.2.2).
• To use the len, min/max, sum, and random.shuffle functions for a list (§10.2.3).
• To access list elements using indexed variables (§10.2.4).
• To obtain a sublist using the slicing operator [start:end] (§10.2.5).
• To use +, *, and in/not in operators on lists (§10.2.6).
• To traverse elements in a list using a for-each loop (§10.2.7).
• To create lists using list comprehension (§10.2.8).
• To compare lists using comparison operators (§10.2.9).
• To split a string to a list using the str’s split method (§10.2.10).
• To use lists in the application development (§§10.3–10.5).
• To copy contents from one list to another (§10.6).
• To develop and invoke functions with list arguments and return value (§10.7–10.9).
• To search elements using the linear (§10.10.1) or binary (§10.10.2) search algorithm.
• To sort a list using the selection sort (§10.11.1)
• To sort a list using the insertion sort (§10.11.2).
• To develop the bouncing ball animation using a list (§10.12).
4ARULKUMAR V Ap/CSE SECE
Creating Lists
5
list1 = list() # Create an empty list
list2 = list([2, 3, 4]) # Create a list with elements 2, 3, 4
list3 = list(["red", "green", "blue"]) # Create a list with strings
list4 = list(range(3, 6)) # Create a list with elements 3, 4, 5
list5 = list("abcd") # Create a list with characters a, b, c
list1 = [] # Same as list()
list2 = [2, 3, 4] # Same as list([2, 3, 4])
list3 = ["red", "green"] # Same as list(["red", "green"])
Creating list using the list class
For convenience, you may create a list using the following syntax:
ARULKUMAR V Ap/CSE SECE
list Methods
6
list
append(x: object): None
insert(index: int, x: object):
None
remove(x: object): None
index(x: object): int
count(x: object): int
sort(): None
reverse(): None
extend(l: list): None
pop([i]): object
Add an item x to the end of the list.
Insert an item x at a given index. Note that the first element in
the list has index 0.
Remove the first occurrence of the item x from the list.
Return the index of the item x in the list.
Return the number of times item x appears in the list.
Sort the items in the list.
Reverse the items in the list.
Append all the items in L to the list.
Remove the item at the given position and return it. The square
bracket denotes that parameter is optional. If no index is
specified, list.pop() removes and returns the last item in the
list.
ARULKUMAR V Ap/CSE SECE
Functions for lists
>>> list1 = [2, 3, 4, 1, 32]
>>> len(list1)
5
>>> max(list1)
32
>>> min(list1)
1
>>> sum(list1)
42
>>> import random
>>> random.shuffle(list1) # Shuffle the items in the list
>>> list1
[4, 1, 2, 32, 3]
7ARULKUMAR V Ap/CSE SECE
Indexer Operator []
8
5.6
4.5
3.3
13.2
4.0
34.33
34.0
45.45
99.993
11123
myList = [5.6, 4.5, 3.3, 13.2, 4.0, 34.33, 34.0, 45.45, 99.993, 11123]
myList reference
myList[0]
myList[1]
myList[2]
myList[3]
myList[4]
myList[5]
myList[6]
myList[7]
myList[8]
myList[9]
Element value
list reference
variable
list element at
index 5
ARULKUMAR V Ap/CSE SECE
The +, *, [ : ], and in Operators
>>> list1 = [2, 3]
>>> list2 = [1, 9]
>>> list3 = list1 + list2
>>> list3
[2, 3, 1, 9]
>>> list3 = 2 * list1
>>> list3
[2, 3, 2, 3, 2, 3]
>>> list4 = list3[2 : 4]
>>> list4
[2, 3]
9ARULKUMAR V Ap/CSE SECE
The +, *, [ : ], and in Operators
>>> list1 = [2, 3, 5, 2, 33, 21]
>>> list1[-1]
21
>>> list1[-3]
2
10
>>> list1 = [2, 3, 5, 2, 33, 21]
>>> 2 in list1
True
>>> list1 = [2, 3, 5, 2, 33, 21]
>>> 2.5 in list1
False
ARULKUMAR V Ap/CSE SECE
off-by-one Error
i = 0
while i <= len(lst):
print(lst[i])
i += 1
11ARULKUMAR V Ap/CSE SECE
List Comprehension
List comprehensions provide a concise way to create items
from sequence. A list comprehension consists of brackets
containing an expression followed by a for clause, then
zero or more for or if clauses. The result will be a list
resulting from evaluating the expression. Here are some
examples:
12
>>> list1 = [x for x range(0, 5)] # Returns a list of 0, 1, 2, 4
>>> list1
[0, 1, 2, 3, 4]
>>> list2 = [0.5 * x for x in list1]
>>> list2
[0.0, 0.5, 1.0, 1.5, 2.0]
>>> list3 = [x for x in list2 if x < 1.5]
>>> list3
[0.0, 0.5, 1.0]
ARULKUMAR V Ap/CSE SECE
Comparing Lists
13
>>>list1 = ["green", "red", "blue"]
>>>list2 = ["red", "blue", "green"]
>>>list2 == list1
False
>>>list2 != list1
True
>>>list2 >= list1
False
>>>list2 > list1
False
>>>list2 < list1
True
>>>list2 <= list1
True
ARULKUMAR V Ap/CSE SECE
Splitting a String to a List
items = "Welcome to the US".split()
print(items)
['Welcome', 'to', 'the', 'US']
items = "34#13#78#45".split("#")
print(items)
['34', '13', '78', '45']
14ARULKUMAR V Ap/CSE SECE
Problem: Lotto Numbers
Suppose you play the Pick-10 lotto. Each ticket has
10 unique numbers ranging from 1 to 99. You buy
a lot of tickets. You like to have your tickets to
cover all numbers from 1 to 99. Write a program
that reads the ticket numbers from a file and
checks whether all numbers are covered. Assume
the last number in the file is 0.
15
LottoNumbers RunLotto Numbers Sample Data
ARULKUMAR V Ap/CSE SECE
Problem: Lotto Numbers
16
False
False
False
False
.
.
.
False
False
isCovered
[0]
[1]
[2]
[3]
[98]
(a)
[97]
True
False
False
False
.
.
.
False
False
isCovered
[0]
[1]
[2]
[3]
[98]
(b)
[97]
True
True
False
False
.
.
.
False
False
isCovered
[0]
[1]
[2]
[3]
[98]
(c)
[97]
True
True
True
False
.
.
.
False
False
isCovered
[0]
[1]
[2]
[3]
[98]
(d)
[97]
True
True
True
False
.
.
.
False
True
isCovered
[0]
[1]
[2]
[3]
[98]
(e)
[97]
ARULKUMAR V Ap/CSE SECE
Problem: Deck of Cards
The problem is to write a program that picks four cards
randomly from a deck of 52 cards. All the cards can be
represented using a list named deck, filled with initial
values 0 to 51, as follows:
deck = [x for x in range(0, 52)]
17
DeckOfCards Run
ARULKUMAR V Ap/CSE SECE
Problem: Deck of Cards, cont.
18
0
.
.
.
12
13
.
.
.
25
26
.
.
.
38
39
.
.
.
51
13 Spades (♠)
13 Hearts (♥)
13 Diamonds (♦)
13 Clubs (♣)
0
.
.
.
12
13
.
.
.
25
26
.
.
.
38
39
.
.
.
51
deck
[0]
.
.
.
[12]
[13]
.
.
.
[25]
[26]
.
.
.
[38]
[39]
.
.
.
[51]
Random shuffle
6
48
11
24
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
deck
[0]
[1]
[2]
[3]
[4]
[5]
.
.
.
[25]
[26]
.
.
.
[38]
[39]
.
.
.
[51]
Card number 6 is the
7 (6 % 13 = 6) of
Spades (7 / 13 is 0)
Card number 48 is the
10 (48 % 13 = 9) of
Clubs (48 / 13 is 3)
Card number 11 is the
Queen (11 % 13 = 11) of
Spades (11 / 13 is 0)
Card number 24 is the
Queen (24 % 13 = 11) of
Hearts (24 / 13 is 1)
ARULKUMAR V Ap/CSE SECE
Problem: Deck of Cards, cont.
19
cardNumber / 13 =
0 Spades
1 Hearts
2 Diamonds
3 Clubs
cardNumber % 13 =
0 Ace
1 2
.
.
10 Jack
11 Queen
12 King
DeckOfCards Run
ARULKUMAR V Ap/CSE SECE
GUI: Deck of Cards
20
DeckOfCardsDeckOfCardsGUI
ARULKUMAR V Ap/CSE SECE
Copying Lists
Often, in a program, you need to duplicate a list or a part
of a list. In such cases you could attempt to use the
assignment statement (=), as follows:
list2 = list1;
21
Contents
of list1
list1
Contents
of list2
list2
Before the assignment
list2 = list1;
Contents
of list1
list1
Contents
of list2
list2
After the assignment
list2 = list1;
Garbage
ARULKUMAR V Ap/CSE SECE
Passing Lists to Functios
def printList(lst):
for element in lst:
print(element)
22
Invoke the function
lst = [3, 1, 2, 6, 4, 2]
printList(lst)
Invoke the function
printList([3, 1, 2, 6, 4, 2])
Anonymous list
ARULKUMAR V Ap/CSE SECE
Pass By Value
Python uses pass-by-value to pass arguments to a
function. There are important differences between
passing the values of variables of numbers and
strings and passing lists.
Immutable objects
Changeable objects
23ARULKUMAR V Ap/CSE SECE
Pass By Value (Immutable objects)
For an argument of a number or a string, the
original value of the number and string outside the
function is not changed, because numbers and
strings are immutable in Python.
24ARULKUMAR V Ap/CSE SECE
Pass By Value (changeable objects)
For an argument of a list, the value of the
argument is a reference to a list; this reference
value is passed to the function. Semantically, it can
be best described as pass-by-sharing, i.e., the list in
the function is the same as the list being passed. So
if you change the list in the function, you will see
the change outside the function.
25ARULKUMAR V Ap/CSE SECE
Simple Example
def main():
x = 1 # x represents an int value
y = [1, 2, 3] # y represents a list
m(x, y) # Invoke f with arguments x and y
print("x is " + str(x))
print("y[0] is " + str(y[0]))
def m(number, numbers):
number = 1001 # Assign a new value to number
numbers[0] = 5555 # Assign a new value to numbers[0]
main()
26ARULKUMAR V Ap/CSE SECE
Subtle Issues Regarding Default Arguments
def add(x, lst = []):
if not(x in lst):
lst.append(x)
return lst
list1 = add(1)
print(list1)
list2 = add(2)
print(list2)
list3 = add(3, [11, 12, 13, 14])
print(list3)
list4 = add(4)
print(list4)
27
[1]
[1, 2]
[11, 12, 13, 14]
[1, 2, 4]
Output
default value is
created only once.
ARULKUMAR V Ap/CSE SECE
Returning a List from a Function
list1 = [1, 2, 3, 4, 5, 6]
list2 = reverse(list1)
28
def reverse(list):
result = []
for element in list:
result.insert(0, element)
return result
list
result
Note that list already has the reverse method
list.reverse()
ARULKUMAR V Ap/CSE SECE
Problem: Counting Occurrence of Each Letter
• Generate 100 lowercase
letters randomly and assign
to a list of characters.
• Count the occurrence of
each letter in the list.
29
CountLettersInList Run
…
…
chars[0]
chars[1]
…
…
chars[98]
chars[99]
…
…
counts[0]
counts[1]
…
…
counts[24]
counts[25]
ARULKUMAR V Ap/CSE SECE
Searching Lists
Searching is the process of looking for a specific element in
a list; for example, discovering whether a certain score is
included in a list of scores. Searching is a common task in
computer programming. There are many algorithms and
data structures devoted to searching. In this section, two
commonly used approaches are discussed, linear search
and binary search.
30
# The function for finding a key in the list
def linearSearch(lst, key):
for i in range(0, len(lst)):
if key == lst[i]:
return i
return -1
lst
key Compare key with lst[i] for i = 0, 1, …
[0] [1] [2] …
ARULKUMAR V Ap/CSE SECE
Linear Search
The linear search approach compares the key
element, key, sequentially with each element
in list. The method continues to do so until the
key matches an element in the list or the list is
exhausted without a match being found. If a
match is made, the linear search returns the
index of the element in the list that matches
the key. If no match is found, the search
returns -1.
31ARULKUMAR V Ap/CSE SECE
Linear Search Animation
32
6 4 1 9 7 3 2 8
6 4 1 9 7 3 2 8
6 4 1 9 7 3 2 8
6 4 1 9 7 3 2 8
6 4 1 9 7 3 2 8
6 4 1 9 7 3 2 8
3
3
3
3
3
3
animation
Key List
Linear Search Animation
http://www.cs.armstrong.edu/liang/animation/LinearSea
rchAnimation.html
33
animation
Run
ARULKUMAR V Ap/CSE SECE
Binary Search
For binary search to work, the elements in the
list must already be ordered. Without loss of
generality, assume that the list is in ascending
order.
e.g., 2 4 7 10 11 45 50 59 60 66 69 70 79
The binary search first compares the key with
the element in the middle of the list.
34ARULKUMAR V Ap/CSE SECE
Binary Search, cont.
• If the key is less than the middle element,
you only need to search the key in the first
half of the list.
• If the key is equal to the middle element,
the search ends with a match.
• If the key is greater than the middle
element, you only need to search the key in
the second half of the list.
35
Consider the following three cases:
ARULKUMAR V Ap/CSE SECE
Binary Search
36
1 2 3 4 6 7 8 9
1 2 3 4 6 7 8 9
1 2 3 4 6 7 8 9
8
8
8
Key List
animation
ARULKUMAR V Ap/CSE SECE
Binary Search Animation
http://www.cs.armstrong.edu/liang/animation/BinarySea
rchAnimation.html
37
animation
Run
ARULKUMAR V Ap/CSE SECE
Binary Search, cont.
38
[0] [1] [2] [3] [4] [5] [6] [7] [8] [9] [10] [11] [12]
2 4 7 10 11 45 50 59 60 66 69 70 79
key is 11
key < 50
lst
mid
[0] [1] [2] [3] [4] [5]
key > 7
key == 11
highlow
mid highlow
lst
[3] [4] [5]
mid highlow
lst
2 4 7 10 11 45
10 11 45
ARULKUMAR V Ap/CSE SECE
Binary Search, cont.
39
[0] [1] [2] [3] [4] [5] [6] [7] [8] [9] [10] [11] [12]
2 4 7 10 11 45 50 59 60 66 69 70 79
key is 54
key > 50
lst
mid
[0] [1] [2] [3] [4] [5] [6] [7] [8] [9] [10] [11] [12]
key < 66
key < 59
highlow
mid highlow
lst
[7] [8]
mid highlow
lst
59 60 66 69 70 79
59 60
[6] [7] [8]
highlow
59 60
ARULKUMAR V Ap/CSE SECE
Binary Search, cont.
The binarySearch method returns the index of the
element in the list that matches the search key if it
is contained in the list. Otherwise, it returns
-insertion point - 1.
The insertion point is the point at which the key
would be inserted into the list.
40ARULKUMAR V Ap/CSE SECE
From Idea to Soluton
# Use binary search to find the key in the list
def binarySearch(lst, key):
low = 0
high = len(lst) - 1
while high >= low:
mid = (low + high) // 2
if key < lst[mid]:
high = mid - 1
elif key == lst[mid]:
return mid
else:
low = mid + 1
return –low - 1 # Now high < low, key not found
41ARULKUMAR V Ap/CSE SECE
Sorting Lists
Sorting, like searching, is also a common task in
computer programming. Many different algorithms
have been developed for sorting. This section
introduces two simple, intuitive sorting algorithms:
selection sort and insertion sort.
42ARULKUMAR V Ap/CSE SECE
Selection Sort
Selection sort finds the largest number in the list and places it last. It then finds the
largest number remaining and places it next to last, and so on until the list contains only a
single number. Figure 6.17 shows how to sort the list {2, 9, 5, 4, 8, 1, 6} using selection
sort.
43
2 9 5 4 8 1 6
swap
Select 1 (the smallest) and swap it
with 2 (the first) in the list
1 9 5 4 8 2 6
swap
The number 1 is now in the
correct position and thus no
longer needs to be considered.
1 2 5 4 8 9 6
swap
1 2 4 5 8 9 6
Select 2 (the smallest) and swap it
with 9 (the first) in the remaining
list
The number 2 is now in the
correct position and thus no
longer needs to be considered.
Select 4 (the smallest) and swap it
with 5 (the first) in the remaining
list
The number 6 is now in the
correct position and thus no
longer needs to be considered.
1 2 4 5 8 9 6Select 6 (the smallest) and swap it
with 8 (the first) in the remaining
list
1 2 4 5 6 9 8
swap
The number 6 is now in the
correct position and thus no
longer needs to be considered.
1 2 4 5 6 8 9
Select 8 (the smallest) and swap it
with 9 (the first) in the remaining
list
The number 8 is now in the
correct position and thus no
longer needs to be considered.
Since there is only one element
remaining in the list, sort is
completed
5 is the smallest and in the right
position. No swap is necessary
The number 5 is now in the
correct position and thus no
longer needs to be considered.
swap
ARULKUMAR V Ap/CSE SECE
Selection Sort Animation
http://www.cs.armstrong.edu/liang/animation/Selection
SortAnimation.html
44
animation
Run
ARULKUMAR V Ap/CSE SECE
From Idea to Solution
45
for i in range(0, len(lst)):
select the smallest element in lst[i.. len(lst)-1]
swap the smallest with lst[i], if necessary
# lst[i] is in its correct position.
# The next iteration apply on lst[i+1..len(lst)-1]
lst[0] lst[1] lst[2] lst[3] ... lst[10]
lst[0] lst[1] lst[2] lst[3] ... lst[10]
lst[0] lst[1] lst[2] lst[3] ... lst[10]
lst[0] lst[1] lst[2] lst[3] ... lst[10]
lst[0] lst[1] lst[2] lst[3] ... lst[10]
...
lst[0] lst[1] lst[2] lst[3] ... lst[10]
ARULKUMAR V Ap/CSE SECE
Expand
46
for i in range(0, len(lst)):
select the smallest element in lst[i.. len(lst)-1]
swap the smallest with lst[i], if necessary
# lst[i] is in its correct position.
# The next iteration apply on lst[i+1..len(lst)-1]
currentMin = lst[i]
currentMinIndex = i
for j in range(i + 1, len(lst)):
if currentMin > lst[j]:
currentMin = lst[j]
currentMinIndex = j
ARULKUMAR V Ap/CSE SECE
Expand
47
for i in range(0, len(lst)):
select the smallest element in lst[i.. len(lst)-1]
swap the smallest with lst[i], if necessary
# lst[i] is in its correct position.
# The next iteration apply on lst[i+1..len(lst)-1]
# Find the minimum in the lst[i..len(lst)-1]
currentMin = lst[i]
currentMinIndex = i
for j in range(i + 1, len(lst)):
if currentMin > lst[j]:
currentMin = lst[j]
currentMinIndex = j
# Swap lst[i] with lst[currentMinIndex] if necessary
if currentMinIndex != i:
lst[currentMinIndex] = lst[i]
lst[i] = currentMin ARULKUMAR V Ap/CSE SECE
Wrap it in a Function
48
# The function for sorting the numbers
def selectionSort(lst):
for i in range(0, len(lst) - 1):
# Find the minimum in the lst[i..len(lst)-1]
currentMin = lst[i]
currentMinIndex = i
for j in range(i + 1, len(lst)):
if currentMin > lst[j]:
currentMin = lst[j]
currentMinIndex = j
# Swap lst[i] with lst[currentMinIndex] if necessary
if currentMinIndex != i:
lst[currentMinIndex] = lst[i]
lst[i] = currentMin
Invoke it
selectionSort(yourList)
ARULKUMAR V Ap/CSE SECE
Insertion Sort
myList = [2, 9, 5, 4, 8, 1, 6] # Unsorted
49
The insertion sort
algorithm sorts a list
of values by
repeatedly inserting
an unsorted element
into a sorted sublist
until the whole list
is sorted.
2 9 5 4 8 1 6Step 1: Initially, the sorted sublist contains the
first element in the list. Insert 9 into the sublist.
2 9 5 4 8 1 6Step2: The sorted sublist is [2, 9]. Insert 5 into the
sublist.
2 5 9 4 8 1 6Step 3: The sorted sublist is [2, 5, 9]. Insert 4 into
the sublist.
2 4 5 9 8 1 6Step 4: The sorted sublist is [2, 4, 5, 9]. Insert 8
into the sublist.
2 4 5 8 9 1 6Step 5: The sorted sublist is [2, 4, 5, 8, 9]. Insert
1 into the sublist.
1 2 4 5 8 9 6Step 6: The sorted sublist is [1, 2, 4, 5, 8, 9].
Insert 6 into the sublist.
1 2 4 5 6 8 9Step 7: The entire list is now sorted
ARULKUMAR V Ap/CSE SECE
Insertion Sort Animation
http://www.cs.armstrong.edu/liang/animation/Insertion
SortAnimation.html
50
animation
Run
ARULKUMAR V Ap/CSE SECE
Insertion Sort
myList = [2, 9, 5, 4, 8, 1, 6] # Unsorted
51
2 9 5 4 8 1 6
2 9 5 4 8 1 6
2 5 9 4 8 1 6
2 4 5 8 9 1 6
1 2 4 5 8 9 6
2 4 5 9 8 1 6
1 2 4 5 6 8 9
animation
ARULKUMAR V Ap/CSE SECE
How to Insert?
52
The insertion sort
algorithm sorts a list
of values by
repeatedly inserting
an unsorted element
into a sorted sublist
until the whole list
is sorted.
[0] [1] [2] [3] [4] [5] [6]
2 5 9 4list Step 1: Save 4 to a temporary variable currentElement
[0] [1] [2] [3] [4] [5] [6]
2 5 9list Step 2: Move list[2] to list[3]
[0] [1] [2] [3] [4] [5] [6]
2 5 9list Step 3: Move list[1] to list[2]
[0] [1] [2] [3] [4] [5] [6]
2 4 5 9list Step 4: Assign currentElement to list[1]
ARULKUMAR V Ap/CSE SECE
From Idea to Solution
53
for i in range(1, len(lst)):
insert lst[i] into a sorted sublist lst[0..i-1] so that
lst[0..i] is sorted.
lst[0]
lst[0] lst[1]
lst[0] lst[1] lst[2]
lst[0] lst[1] lst[2] lst[3]
lst[0] lst[1] lst[2] lst[3] ...
ARULKUMAR V Ap/CSE SECE
From Idea to Solution
54
for i in range(1, len(lst)):
insert lst[i] into a sorted sublist lst[0..i-1] so that
lst[0..i] is sorted.
InsertSort
Expand
k = i - 1
while k >= 0 and lst[k] > currentElement:
lst[k + 1] = lst[k]
k -= 1
# Insert the current element into lst[k + 1]
lst[k + 1] = currentElement
ARULKUMAR V Ap/CSE SECE
Case Studies: Bouncing Balls
55
BouncingBalls Run
Ball
x: int
y: int
dx: int
dy: int
color: Color
radius: int
The x-, y-coordinates for the center of the
ball. By default, it is (0, 0).
dx and dy are the increment for (x, y).
The color of the ball.
The radius of the ball.
ARULKUMAR V Ap/CSE SECE

More Related Content

What's hot

Sql
SqlSql
Sql Karunakaran Mallikeswaran
 
Sql Tags
Sql TagsSql Tags
Sql Tags Sutharsan nagarajan
 
Numpy cheat-sheet
Numpy cheat-sheetNumpy cheat-sheet
Numpy cheat-sheet Arief Kurniawan
 
Perl names values and variables
Perl names values and variablesPerl names values and variables
Perl names values and variables sana mateen
 
MYSQL
MYSQLMYSQL
MYSQL ARJUN
 
Les10
Les10Les10
Les10 arnold 7490
 
Php Using Arrays
Php Using ArraysPhp Using Arrays
Php Using Arrays mussawir20
 
Sets
SetsSets
Sets Lakshmi Sarvani Videla
 
Class 4 - PHP Arrays
Class 4 - PHP ArraysClass 4 - PHP Arrays
Class 4 - PHP Arrays Ahmed Swilam
 
Php array
Php arrayPhp array
Php array Core Lee
 
Arrays in PHP
Arrays in PHPArrays in PHP
Arrays in PHP Compare Infobase Limited
 
iRODS Rule Language Cheat Sheet
iRODS Rule Language Cheat SheetiRODS Rule Language Cheat Sheet
iRODS Rule Language Cheat Sheet Samuel Lampa
 
学生向けScalaハンズオンテキスト
学生向けScalaハンズオンテキスト学生向けScalaハンズオンテキスト
学生向けScalaハンズオンテキスト Opt Technologies
 
Php array
Php arrayPhp array
Php array Nikul Shah
 
PHP 101
PHP 101 PHP 101
PHP 101 Muhammad Hijazi
 
Python Collection datatypes
Python Collection datatypesPython Collection datatypes
Python Collection datatypes Adheetha O. V
 
My sql Syntax
My sql SyntaxMy sql Syntax
My sql Syntax Reka
 
The Ring programming language version 1.8 book - Part 27 of 202
The Ring programming language version 1.8 book - Part 27 of 202The Ring programming language version 1.8 book - Part 27 of 202
The Ring programming language version 1.8 book - Part 27 of 202 Mahmoud Samir Fayed
 
Arrays in PHP
Arrays in PHPArrays in PHP
Arrays in PHP Vineet Kumar Saini
 

What's hot (19)

Sql
SqlSql
Sql
 
Sql Tags
Sql TagsSql Tags
Sql Tags
 
Numpy cheat-sheet
Numpy cheat-sheetNumpy cheat-sheet
Numpy cheat-sheet
 
Perl names values and variables
Perl names values and variablesPerl names values and variables
Perl names values and variables
 
MYSQL
MYSQLMYSQL
MYSQL
 
Les10
Les10Les10
Les10
 
Php Using Arrays
Php Using ArraysPhp Using Arrays
Php Using Arrays
 
Sets
SetsSets
Sets
 
Class 4 - PHP Arrays
Class 4 - PHP ArraysClass 4 - PHP Arrays
Class 4 - PHP Arrays
 
Php array
Php arrayPhp array
Php array
 
Arrays in PHP
Arrays in PHPArrays in PHP
Arrays in PHP
 
iRODS Rule Language Cheat Sheet
iRODS Rule Language Cheat SheetiRODS Rule Language Cheat Sheet
iRODS Rule Language Cheat Sheet
 
学生向けScalaハンズオンテキスト
学生向けScalaハンズオンテキスト学生向けScalaハンズオンテキスト
学生向けScalaハンズオンテキスト
 
Php array
Php arrayPhp array
Php array
 
PHP 101
PHP 101 PHP 101
PHP 101
 
Python Collection datatypes
Python Collection datatypesPython Collection datatypes
Python Collection datatypes
 
My sql Syntax
My sql SyntaxMy sql Syntax
My sql Syntax
 
The Ring programming language version 1.8 book - Part 27 of 202
The Ring programming language version 1.8 book - Part 27 of 202The Ring programming language version 1.8 book - Part 27 of 202
The Ring programming language version 1.8 book - Part 27 of 202
 
Arrays in PHP
Arrays in PHPArrays in PHP
Arrays in PHP
 

Similar to 6. list

python_avw - Unit-03.pdf
python_avw - Unit-03.pdfpython_avw - Unit-03.pdf
python_avw - Unit-03.pdf AshaWankar1
 
Unit - 4.ppt
Unit - 4.pptUnit - 4.ppt
Unit - 4.ppt Kongunadu College of Engineering and Technology
 
Lists.pptx
Lists.pptxLists.pptx
Lists.pptx Yagna15
 
Module-2.pptx
Module-2.pptxModule-2.pptx
Module-2.pptx GaganRaj28
 
The Ring programming language version 1.5.3 book - Part 22 of 184
The Ring programming language version 1.5.3 book - Part 22 of 184The Ring programming language version 1.5.3 book - Part 22 of 184
The Ring programming language version 1.5.3 book - Part 22 of 184 Mahmoud Samir Fayed
 
Pytho lists
Pytho listsPytho lists
Pytho lists BMS Institute of Technology and Management
 
Python lists
Python listsPython lists
Python lists nuripatidar
 
Pythonlearn-08-Lists.pptx
Pythonlearn-08-Lists.pptxPythonlearn-08-Lists.pptx
Pythonlearn-08-Lists.pptx MihirDatir1
 
Pythonlearn-08-Lists.pptx
Pythonlearn-08-Lists.pptxPythonlearn-08-Lists.pptx
Pythonlearn-08-Lists.pptx MihirDatir
 
Unit 4 python -list methods
Unit 4   python -list methodsUnit 4   python -list methods
Unit 4 python -list methods narmadhakin
 
GE3151 PSPP UNIT IV QUESTION BANK.docx.pdf
GE3151 PSPP UNIT IV QUESTION BANK.docx.pdfGE3151 PSPP UNIT IV QUESTION BANK.docx.pdf
GE3151 PSPP UNIT IV QUESTION BANK.docx.pdf Asst.prof M.Gokilavani
 
Module III.pdf
Module III.pdfModule III.pdf
Module III.pdf R.K.College of engg & Tech
 
Python for Beginners(v3)
Python for Beginners(v3)Python for Beginners(v3)
Python for Beginners(v3) Panimalar Engineering College
 
Map, Reduce and Filter in Swift
Map, Reduce and Filter in SwiftMap, Reduce and Filter in Swift
Map, Reduce and Filter in Swift Aleksandras Smirnovas
 
Python lists &amp; sets
Python lists &amp; setsPython lists &amp; sets
Python lists &amp; sets Aswini Dharmaraj
 
GE3151_PSPP_UNIT_4_Notes
GE3151_PSPP_UNIT_4_NotesGE3151_PSPP_UNIT_4_Notes
GE3151_PSPP_UNIT_4_Notes Asst.prof M.Gokilavani
 
The Ring programming language version 1.9 book - Part 29 of 210
The Ring programming language version 1.9 book - Part 29 of 210The Ring programming language version 1.9 book - Part 29 of 210
The Ring programming language version 1.9 book - Part 29 of 210 Mahmoud Samir Fayed
 
List_tuple_dictionary.pptx
List_tuple_dictionary.pptxList_tuple_dictionary.pptx
List_tuple_dictionary.pptx ChandanVatsa2
 
The Ring programming language version 1.7 book - Part 26 of 196
The Ring programming language version 1.7 book - Part 26 of 196The Ring programming language version 1.7 book - Part 26 of 196
The Ring programming language version 1.7 book - Part 26 of 196 Mahmoud Samir Fayed
 
Python Unit 5 Questions n Notes.pdf
Python Unit 5 Questions n Notes.pdfPython Unit 5 Questions n Notes.pdf
Python Unit 5 Questions n Notes.pdf MCCMOTOR
 

Similar to 6. list (20)

python_avw - Unit-03.pdf
python_avw - Unit-03.pdfpython_avw - Unit-03.pdf
python_avw - Unit-03.pdf
 
Unit - 4.ppt
Unit - 4.pptUnit - 4.ppt
Unit - 4.ppt
 
Lists.pptx
Lists.pptxLists.pptx
Lists.pptx
 
Module-2.pptx
Module-2.pptxModule-2.pptx
Module-2.pptx
 
The Ring programming language version 1.5.3 book - Part 22 of 184
The Ring programming language version 1.5.3 book - Part 22 of 184The Ring programming language version 1.5.3 book - Part 22 of 184
The Ring programming language version 1.5.3 book - Part 22 of 184
 
Pytho lists
Pytho listsPytho lists
Pytho lists
 
Python lists
Python listsPython lists
Python lists
 
Pythonlearn-08-Lists.pptx
Pythonlearn-08-Lists.pptxPythonlearn-08-Lists.pptx
Pythonlearn-08-Lists.pptx
 
Pythonlearn-08-Lists.pptx
Pythonlearn-08-Lists.pptxPythonlearn-08-Lists.pptx
Pythonlearn-08-Lists.pptx
 
Unit 4 python -list methods
Unit 4   python -list methodsUnit 4   python -list methods
Unit 4 python -list methods
 
GE3151 PSPP UNIT IV QUESTION BANK.docx.pdf
GE3151 PSPP UNIT IV QUESTION BANK.docx.pdfGE3151 PSPP UNIT IV QUESTION BANK.docx.pdf
GE3151 PSPP UNIT IV QUESTION BANK.docx.pdf
 
Module III.pdf
Module III.pdfModule III.pdf
Module III.pdf
 
Python for Beginners(v3)
Python for Beginners(v3)Python for Beginners(v3)
Python for Beginners(v3)
 
Map, Reduce and Filter in Swift
Map, Reduce and Filter in SwiftMap, Reduce and Filter in Swift
Map, Reduce and Filter in Swift
 
Python lists &amp; sets
Python lists &amp; setsPython lists &amp; sets
Python lists &amp; sets
 
GE3151_PSPP_UNIT_4_Notes
GE3151_PSPP_UNIT_4_NotesGE3151_PSPP_UNIT_4_Notes
GE3151_PSPP_UNIT_4_Notes
 
The Ring programming language version 1.9 book - Part 29 of 210
The Ring programming language version 1.9 book - Part 29 of 210The Ring programming language version 1.9 book - Part 29 of 210
The Ring programming language version 1.9 book - Part 29 of 210
 
List_tuple_dictionary.pptx
List_tuple_dictionary.pptxList_tuple_dictionary.pptx
List_tuple_dictionary.pptx
 
The Ring programming language version 1.7 book - Part 26 of 196
The Ring programming language version 1.7 book - Part 26 of 196The Ring programming language version 1.7 book - Part 26 of 196
The Ring programming language version 1.7 book - Part 26 of 196
 
Python Unit 5 Questions n Notes.pdf
Python Unit 5 Questions n Notes.pdfPython Unit 5 Questions n Notes.pdf
Python Unit 5 Questions n Notes.pdf
 

More from PhD Research Scholar

Ajax
AjaxAjax
Ajax PhD Research Scholar
 
Quiz servlet
Quiz servletQuiz servlet
Quiz servlet PhD Research Scholar
 
Quiz
QuizQuiz
Quiz PhD Research Scholar
 
servlet db connectivity
servlet db connectivityservlet db connectivity
servlet db connectivity PhD Research Scholar
 
2.java script dom
2.java script  dom2.java script  dom
2.java script dom PhD Research Scholar
 
1.java script
1.java script1.java script
1.java script PhD Research Scholar
 
Quiz javascript
Quiz javascriptQuiz javascript
Quiz javascript PhD Research Scholar
 
Thread&amp;multithread
Thread&amp;multithreadThread&amp;multithread
Thread&amp;multithread PhD Research Scholar
 
String
StringString
String PhD Research Scholar
 
Streams&amp;io
Streams&amp;ioStreams&amp;io
Streams&amp;io PhD Research Scholar
 
Packages
PackagesPackages
Packages PhD Research Scholar
 
Interface in java
Interface in javaInterface in java
Interface in java PhD Research Scholar
 
Inner classes in java
Inner classes in javaInner classes in java
Inner classes in java PhD Research Scholar
 
Inheritance
InheritanceInheritance
Inheritance PhD Research Scholar
 
Exception handling
Exception handlingException handling
Exception handling PhD Research Scholar
 
Applets
AppletsApplets
Applets PhD Research Scholar
 
Abstract class
Abstract classAbstract class
Abstract class PhD Research Scholar
 
5. string
5. string5. string
5. string PhD Research Scholar
 
4. functions
4. functions4. functions
4. functions PhD Research Scholar
 
3.2 looping statement
3.2 looping statement3.2 looping statement
3.2 looping statement PhD Research Scholar
 

More from PhD Research Scholar (20)

Ajax
AjaxAjax
Ajax
 
Quiz servlet
Quiz servletQuiz servlet
Quiz servlet
 
Quiz
QuizQuiz
Quiz
 
servlet db connectivity
servlet db connectivityservlet db connectivity
servlet db connectivity
 
2.java script dom
2.java script  dom2.java script  dom
2.java script dom
 
1.java script
1.java script1.java script
1.java script
 
Quiz javascript
Quiz javascriptQuiz javascript
Quiz javascript
 
Thread&amp;multithread
Thread&amp;multithreadThread&amp;multithread
Thread&amp;multithread
 
String
StringString
String
 
Streams&amp;io
Streams&amp;ioStreams&amp;io
Streams&amp;io
 
Packages
PackagesPackages
Packages
 
Interface in java
Interface in javaInterface in java
Interface in java
 
Inner classes in java
Inner classes in javaInner classes in java
Inner classes in java
 
Inheritance
InheritanceInheritance
Inheritance
 
Exception handling
Exception handlingException handling
Exception handling
 
Applets
AppletsApplets
Applets
 
Abstract class
Abstract classAbstract class
Abstract class
 
5. string
5. string5. string
5. string
 
4. functions
4. functions4. functions
4. functions
 
3.2 looping statement
3.2 looping statement3.2 looping statement
3.2 looping statement
 

Recently uploaded

Crayon Activity Handout For the Crayon A
Crayon Activity Handout For the Crayon ACrayon Activity Handout For the Crayon A
Crayon Activity Handout For the Crayon A UnboundStockton
 
MARGINALIZATION (Different learners in Marginalized Group
MARGINALIZATION (Different learners in Marginalized GroupMARGINALIZATION (Different learners in Marginalized Group
MARGINALIZATION (Different learners in Marginalized Group JonathanParaisoCruz
 
TataKelola dan KamSiber Kecerdasan Buatan v022.pdf
TataKelola dan KamSiber Kecerdasan Buatan v022.pdfTataKelola dan KamSiber Kecerdasan Buatan v022.pdf
TataKelola dan KamSiber Kecerdasan Buatan v022.pdf Sarwono Sutikno, Dr.Eng.,CISA,CISSP,CISM,CSX-F
 
18-04-UA_REPORT_MEDIALITERAСY_INDEX-DM_23-1-final-eng.pdf
18-04-UA_REPORT_MEDIALITERAСY_INDEX-DM_23-1-final-eng.pdf18-04-UA_REPORT_MEDIALITERAСY_INDEX-DM_23-1-final-eng.pdf
18-04-UA_REPORT_MEDIALITERAСY_INDEX-DM_23-1-final-eng.pdf ssuser54595a
 
How to Configure Email Server in Odoo 17
How to Configure Email Server in Odoo 17How to Configure Email Server in Odoo 17
How to Configure Email Server in Odoo 17 Celine George
 
Solving Puzzles Benefits Everyone (English).pptx
Solving Puzzles Benefits Everyone (English).pptxSolving Puzzles Benefits Everyone (English).pptx
Solving Puzzles Benefits Everyone (English).pptx OH TEIK BIN
 
Alper Gobel In Media Res Media Component
Alper Gobel In Media Res Media ComponentAlper Gobel In Media Res Media Component
Alper Gobel In Media Res Media Component InMediaRes1
 
Computed Fields and api Depends in the Odoo 17
Computed Fields and api Depends in the Odoo 17Computed Fields and api Depends in the Odoo 17
Computed Fields and api Depends in the Odoo 17 Celine George
 
EPANDING THE CONTENT OF AN OUTLINE using notes.pptx
EPANDING THE CONTENT OF AN OUTLINE using notes.pptxEPANDING THE CONTENT OF AN OUTLINE using notes.pptx
EPANDING THE CONTENT OF AN OUTLINE using notes.pptx RaymartEstabillo3
 
Enzyme, Pharmaceutical Aids, Miscellaneous Last Part of Chapter no 5th.pdf
Enzyme, Pharmaceutical Aids, Miscellaneous Last Part of Chapter no 5th.pdfEnzyme, Pharmaceutical Aids, Miscellaneous Last Part of Chapter no 5th.pdf
Enzyme, Pharmaceutical Aids, Miscellaneous Last Part of Chapter no 5th.pdf Sumit Tiwari
 
Types of Journalistic Writing Grade 8.pptx
Types of Journalistic Writing Grade 8.pptxTypes of Journalistic Writing Grade 8.pptx
Types of Journalistic Writing Grade 8.pptx Eyham Joco
 
How to Make a Pirate ship Primary Education.pptx
How to Make a Pirate ship Primary Education.pptxHow to Make a Pirate ship Primary Education.pptx
How to Make a Pirate ship Primary Education.pptx manuelaromero2013
 
9953330565 Low Rate Call Girls In Rohini Delhi NCR
9953330565 Low Rate Call Girls In Rohini  Delhi NCR9953330565 Low Rate Call Girls In Rohini  Delhi NCR
9953330565 Low Rate Call Girls In Rohini Delhi NCR 9953056974 Low Rate Call Girls In Saket, Delhi NCR
 
Roles & Responsibilities in Pharmacovigilance
Roles & Responsibilities in PharmacovigilanceRoles & Responsibilities in Pharmacovigilance
Roles & Responsibilities in Pharmacovigilance SamikshaHamane
 
Introduction to ArtificiaI Intelligence in Higher Education
Introduction to ArtificiaI Intelligence in Higher EducationIntroduction to ArtificiaI Intelligence in Higher Education
Introduction to ArtificiaI Intelligence in Higher Education pboyjonauth
 
Software Engineering Methodologies (overview)
Software Engineering Methodologies (overview)Software Engineering Methodologies (overview)
Software Engineering Methodologies (overview) eniolaolutunde
 
Interactive Powerpoint_How to Master effective communication
Interactive Powerpoint_How to Master effective communicationInteractive Powerpoint_How to Master effective communication
Interactive Powerpoint_How to Master effective communication nomboosow
 
ESSENTIAL of (CS/IT/IS) class 06 (database)
ESSENTIAL of (CS/IT/IS) class 06 (database)ESSENTIAL of (CS/IT/IS) class 06 (database)
ESSENTIAL of (CS/IT/IS) class 06 (database) Dr. Mazin Mohamed alkathiri
 
Model Call Girl in Bikash Puri Delhi reach out to us at 🔝9953056974🔝
Model Call Girl in Bikash Puri  Delhi reach out to us at 🔝9953056974🔝Model Call Girl in Bikash Puri  Delhi reach out to us at 🔝9953056974🔝
Model Call Girl in Bikash Puri Delhi reach out to us at 🔝9953056974🔝 9953056974 Low Rate Call Girls In Saket, Delhi NCR
 
Organic Name Reactions for the students and aspirants of Chemistry12th.pptx
Organic Name Reactions  for the students and aspirants of Chemistry12th.pptxOrganic Name Reactions  for the students and aspirants of Chemistry12th.pptx
Organic Name Reactions for the students and aspirants of Chemistry12th.pptx VS Mahajan Coaching Centre
 

Recently uploaded (20)

Crayon Activity Handout For the Crayon A
Crayon Activity Handout For the Crayon ACrayon Activity Handout For the Crayon A
Crayon Activity Handout For the Crayon A
 
MARGINALIZATION (Different learners in Marginalized Group
MARGINALIZATION (Different learners in Marginalized GroupMARGINALIZATION (Different learners in Marginalized Group
MARGINALIZATION (Different learners in Marginalized Group
 
TataKelola dan KamSiber Kecerdasan Buatan v022.pdf
TataKelola dan KamSiber Kecerdasan Buatan v022.pdfTataKelola dan KamSiber Kecerdasan Buatan v022.pdf
TataKelola dan KamSiber Kecerdasan Buatan v022.pdf
 
18-04-UA_REPORT_MEDIALITERAСY_INDEX-DM_23-1-final-eng.pdf
18-04-UA_REPORT_MEDIALITERAСY_INDEX-DM_23-1-final-eng.pdf18-04-UA_REPORT_MEDIALITERAСY_INDEX-DM_23-1-final-eng.pdf
18-04-UA_REPORT_MEDIALITERAСY_INDEX-DM_23-1-final-eng.pdf
 
How to Configure Email Server in Odoo 17
How to Configure Email Server in Odoo 17How to Configure Email Server in Odoo 17
How to Configure Email Server in Odoo 17
 
Solving Puzzles Benefits Everyone (English).pptx
Solving Puzzles Benefits Everyone (English).pptxSolving Puzzles Benefits Everyone (English).pptx
Solving Puzzles Benefits Everyone (English).pptx
 
Alper Gobel In Media Res Media Component
Alper Gobel In Media Res Media ComponentAlper Gobel In Media Res Media Component
Alper Gobel In Media Res Media Component
 
Computed Fields and api Depends in the Odoo 17
Computed Fields and api Depends in the Odoo 17Computed Fields and api Depends in the Odoo 17
Computed Fields and api Depends in the Odoo 17
 
EPANDING THE CONTENT OF AN OUTLINE using notes.pptx
EPANDING THE CONTENT OF AN OUTLINE using notes.pptxEPANDING THE CONTENT OF AN OUTLINE using notes.pptx
EPANDING THE CONTENT OF AN OUTLINE using notes.pptx
 
Enzyme, Pharmaceutical Aids, Miscellaneous Last Part of Chapter no 5th.pdf
Enzyme, Pharmaceutical Aids, Miscellaneous Last Part of Chapter no 5th.pdfEnzyme, Pharmaceutical Aids, Miscellaneous Last Part of Chapter no 5th.pdf
Enzyme, Pharmaceutical Aids, Miscellaneous Last Part of Chapter no 5th.pdf
 
Types of Journalistic Writing Grade 8.pptx
Types of Journalistic Writing Grade 8.pptxTypes of Journalistic Writing Grade 8.pptx
Types of Journalistic Writing Grade 8.pptx
 
How to Make a Pirate ship Primary Education.pptx
How to Make a Pirate ship Primary Education.pptxHow to Make a Pirate ship Primary Education.pptx
How to Make a Pirate ship Primary Education.pptx
 
9953330565 Low Rate Call Girls In Rohini Delhi NCR
9953330565 Low Rate Call Girls In Rohini  Delhi NCR9953330565 Low Rate Call Girls In Rohini  Delhi NCR
9953330565 Low Rate Call Girls In Rohini Delhi NCR
 
Roles & Responsibilities in Pharmacovigilance
Roles & Responsibilities in PharmacovigilanceRoles & Responsibilities in Pharmacovigilance
Roles & Responsibilities in Pharmacovigilance
 
Introduction to ArtificiaI Intelligence in Higher Education
Introduction to ArtificiaI Intelligence in Higher EducationIntroduction to ArtificiaI Intelligence in Higher Education
Introduction to ArtificiaI Intelligence in Higher Education
 
Software Engineering Methodologies (overview)
Software Engineering Methodologies (overview)Software Engineering Methodologies (overview)
Software Engineering Methodologies (overview)
 
Interactive Powerpoint_How to Master effective communication
Interactive Powerpoint_How to Master effective communicationInteractive Powerpoint_How to Master effective communication
Interactive Powerpoint_How to Master effective communication
 
ESSENTIAL of (CS/IT/IS) class 06 (database)
ESSENTIAL of (CS/IT/IS) class 06 (database)ESSENTIAL of (CS/IT/IS) class 06 (database)
ESSENTIAL of (CS/IT/IS) class 06 (database)
 
Model Call Girl in Bikash Puri Delhi reach out to us at 🔝9953056974🔝
Model Call Girl in Bikash Puri  Delhi reach out to us at 🔝9953056974🔝Model Call Girl in Bikash Puri  Delhi reach out to us at 🔝9953056974🔝
Model Call Girl in Bikash Puri Delhi reach out to us at 🔝9953056974🔝
 
Organic Name Reactions for the students and aspirants of Chemistry12th.pptx
Organic Name Reactions  for the students and aspirants of Chemistry12th.pptxOrganic Name Reactions  for the students and aspirants of Chemistry12th.pptx
Organic Name Reactions for the students and aspirants of Chemistry12th.pptx
 

6. list

  • 1. 6. List 1ARULKUMAR V Ap/CSE SECE
  • 2. Opening Problem Read one hundred numbers, compute their average, and find out how many numbers are above the average. 2ARULKUMAR V Ap/CSE SECE
  • 3. Solution 3 DataAnalysis Run ARULKUMAR V Ap/CSE SECE
  • 4. Objectives • To describe why lists are useful in programming (§10.1). • To create lists (§10.2.1). • To invoke list’s append, insert, extend, remove, pop, index, count, sort, reverse methods (§10.2.2). • To use the len, min/max, sum, and random.shuffle functions for a list (§10.2.3). • To access list elements using indexed variables (§10.2.4). • To obtain a sublist using the slicing operator [start:end] (§10.2.5). • To use +, *, and in/not in operators on lists (§10.2.6). • To traverse elements in a list using a for-each loop (§10.2.7). • To create lists using list comprehension (§10.2.8). • To compare lists using comparison operators (§10.2.9). • To split a string to a list using the str’s split method (§10.2.10). • To use lists in the application development (§§10.3–10.5). • To copy contents from one list to another (§10.6). • To develop and invoke functions with list arguments and return value (§10.7–10.9). • To search elements using the linear (§10.10.1) or binary (§10.10.2) search algorithm. • To sort a list using the selection sort (§10.11.1) • To sort a list using the insertion sort (§10.11.2). • To develop the bouncing ball animation using a list (§10.12). 4ARULKUMAR V Ap/CSE SECE
  • 5. Creating Lists 5 list1 = list() # Create an empty list list2 = list([2, 3, 4]) # Create a list with elements 2, 3, 4 list3 = list(["red", "green", "blue"]) # Create a list with strings list4 = list(range(3, 6)) # Create a list with elements 3, 4, 5 list5 = list("abcd") # Create a list with characters a, b, c list1 = [] # Same as list() list2 = [2, 3, 4] # Same as list([2, 3, 4]) list3 = ["red", "green"] # Same as list(["red", "green"]) Creating list using the list class For convenience, you may create a list using the following syntax: ARULKUMAR V Ap/CSE SECE
  • 6. list Methods 6 list append(x: object): None insert(index: int, x: object): None remove(x: object): None index(x: object): int count(x: object): int sort(): None reverse(): None extend(l: list): None pop([i]): object Add an item x to the end of the list. Insert an item x at a given index. Note that the first element in the list has index 0. Remove the first occurrence of the item x from the list. Return the index of the item x in the list. Return the number of times item x appears in the list. Sort the items in the list. Reverse the items in the list. Append all the items in L to the list. Remove the item at the given position and return it. The square bracket denotes that parameter is optional. If no index is specified, list.pop() removes and returns the last item in the list. ARULKUMAR V Ap/CSE SECE
  • 7. Functions for lists >>> list1 = [2, 3, 4, 1, 32] >>> len(list1) 5 >>> max(list1) 32 >>> min(list1) 1 >>> sum(list1) 42 >>> import random >>> random.shuffle(list1) # Shuffle the items in the list >>> list1 [4, 1, 2, 32, 3] 7ARULKUMAR V Ap/CSE SECE
  • 8. Indexer Operator [] 8 5.6 4.5 3.3 13.2 4.0 34.33 34.0 45.45 99.993 11123 myList = [5.6, 4.5, 3.3, 13.2, 4.0, 34.33, 34.0, 45.45, 99.993, 11123] myList reference myList[0] myList[1] myList[2] myList[3] myList[4] myList[5] myList[6] myList[7] myList[8] myList[9] Element value list reference variable list element at index 5 ARULKUMAR V Ap/CSE SECE
  • 9. The +, *, [ : ], and in Operators >>> list1 = [2, 3] >>> list2 = [1, 9] >>> list3 = list1 + list2 >>> list3 [2, 3, 1, 9] >>> list3 = 2 * list1 >>> list3 [2, 3, 2, 3, 2, 3] >>> list4 = list3[2 : 4] >>> list4 [2, 3] 9ARULKUMAR V Ap/CSE SECE
  • 10. The +, *, [ : ], and in Operators >>> list1 = [2, 3, 5, 2, 33, 21] >>> list1[-1] 21 >>> list1[-3] 2 10 >>> list1 = [2, 3, 5, 2, 33, 21] >>> 2 in list1 True >>> list1 = [2, 3, 5, 2, 33, 21] >>> 2.5 in list1 False ARULKUMAR V Ap/CSE SECE
  • 11. off-by-one Error i = 0 while i <= len(lst): print(lst[i]) i += 1 11ARULKUMAR V Ap/CSE SECE
  • 12. List Comprehension List comprehensions provide a concise way to create items from sequence. A list comprehension consists of brackets containing an expression followed by a for clause, then zero or more for or if clauses. The result will be a list resulting from evaluating the expression. Here are some examples: 12 >>> list1 = [x for x range(0, 5)] # Returns a list of 0, 1, 2, 4 >>> list1 [0, 1, 2, 3, 4] >>> list2 = [0.5 * x for x in list1] >>> list2 [0.0, 0.5, 1.0, 1.5, 2.0] >>> list3 = [x for x in list2 if x < 1.5] >>> list3 [0.0, 0.5, 1.0] ARULKUMAR V Ap/CSE SECE
  • 13. Comparing Lists 13 >>>list1 = ["green", "red", "blue"] >>>list2 = ["red", "blue", "green"] >>>list2 == list1 False >>>list2 != list1 True >>>list2 >= list1 False >>>list2 > list1 False >>>list2 < list1 True >>>list2 <= list1 True ARULKUMAR V Ap/CSE SECE
  • 14. Splitting a String to a List items = "Welcome to the US".split() print(items) ['Welcome', 'to', 'the', 'US'] items = "34#13#78#45".split("#") print(items) ['34', '13', '78', '45'] 14ARULKUMAR V Ap/CSE SECE
  • 15. Problem: Lotto Numbers Suppose you play the Pick-10 lotto. Each ticket has 10 unique numbers ranging from 1 to 99. You buy a lot of tickets. You like to have your tickets to cover all numbers from 1 to 99. Write a program that reads the ticket numbers from a file and checks whether all numbers are covered. Assume the last number in the file is 0. 15 LottoNumbers RunLotto Numbers Sample Data ARULKUMAR V Ap/CSE SECE
  • 16. Problem: Lotto Numbers 16 False False False False . . . False False isCovered [0] [1] [2] [3] [98] (a) [97] True False False False . . . False False isCovered [0] [1] [2] [3] [98] (b) [97] True True False False . . . False False isCovered [0] [1] [2] [3] [98] (c) [97] True True True False . . . False False isCovered [0] [1] [2] [3] [98] (d) [97] True True True False . . . False True isCovered [0] [1] [2] [3] [98] (e) [97] ARULKUMAR V Ap/CSE SECE
  • 17. Problem: Deck of Cards The problem is to write a program that picks four cards randomly from a deck of 52 cards. All the cards can be represented using a list named deck, filled with initial values 0 to 51, as follows: deck = [x for x in range(0, 52)] 17 DeckOfCards Run ARULKUMAR V Ap/CSE SECE
  • 18. Problem: Deck of Cards, cont. 18 0 . . . 12 13 . . . 25 26 . . . 38 39 . . . 51 13 Spades (♠) 13 Hearts (♥) 13 Diamonds (♦) 13 Clubs (♣) 0 . . . 12 13 . . . 25 26 . . . 38 39 . . . 51 deck [0] . . . [12] [13] . . . [25] [26] . . . [38] [39] . . . [51] Random shuffle 6 48 11 24 . . . . . . . . . . . . . . . . deck [0] [1] [2] [3] [4] [5] . . . [25] [26] . . . [38] [39] . . . [51] Card number 6 is the 7 (6 % 13 = 6) of Spades (7 / 13 is 0) Card number 48 is the 10 (48 % 13 = 9) of Clubs (48 / 13 is 3) Card number 11 is the Queen (11 % 13 = 11) of Spades (11 / 13 is 0) Card number 24 is the Queen (24 % 13 = 11) of Hearts (24 / 13 is 1) ARULKUMAR V Ap/CSE SECE
  • 19. Problem: Deck of Cards, cont. 19 cardNumber / 13 = 0 Spades 1 Hearts 2 Diamonds 3 Clubs cardNumber % 13 = 0 Ace 1 2 . . 10 Jack 11 Queen 12 King DeckOfCards Run ARULKUMAR V Ap/CSE SECE
  • 20. GUI: Deck of Cards 20 DeckOfCardsDeckOfCardsGUI ARULKUMAR V Ap/CSE SECE
  • 21. Copying Lists Often, in a program, you need to duplicate a list or a part of a list. In such cases you could attempt to use the assignment statement (=), as follows: list2 = list1; 21 Contents of list1 list1 Contents of list2 list2 Before the assignment list2 = list1; Contents of list1 list1 Contents of list2 list2 After the assignment list2 = list1; Garbage ARULKUMAR V Ap/CSE SECE
  • 22. Passing Lists to Functios def printList(lst): for element in lst: print(element) 22 Invoke the function lst = [3, 1, 2, 6, 4, 2] printList(lst) Invoke the function printList([3, 1, 2, 6, 4, 2]) Anonymous list ARULKUMAR V Ap/CSE SECE
  • 23. Pass By Value Python uses pass-by-value to pass arguments to a function. There are important differences between passing the values of variables of numbers and strings and passing lists. Immutable objects Changeable objects 23ARULKUMAR V Ap/CSE SECE
  • 24. Pass By Value (Immutable objects) For an argument of a number or a string, the original value of the number and string outside the function is not changed, because numbers and strings are immutable in Python. 24ARULKUMAR V Ap/CSE SECE
  • 25. Pass By Value (changeable objects) For an argument of a list, the value of the argument is a reference to a list; this reference value is passed to the function. Semantically, it can be best described as pass-by-sharing, i.e., the list in the function is the same as the list being passed. So if you change the list in the function, you will see the change outside the function. 25ARULKUMAR V Ap/CSE SECE
  • 26. Simple Example def main(): x = 1 # x represents an int value y = [1, 2, 3] # y represents a list m(x, y) # Invoke f with arguments x and y print("x is " + str(x)) print("y[0] is " + str(y[0])) def m(number, numbers): number = 1001 # Assign a new value to number numbers[0] = 5555 # Assign a new value to numbers[0] main() 26ARULKUMAR V Ap/CSE SECE
  • 27. Subtle Issues Regarding Default Arguments def add(x, lst = []): if not(x in lst): lst.append(x) return lst list1 = add(1) print(list1) list2 = add(2) print(list2) list3 = add(3, [11, 12, 13, 14]) print(list3) list4 = add(4) print(list4) 27 [1] [1, 2] [11, 12, 13, 14] [1, 2, 4] Output default value is created only once. ARULKUMAR V Ap/CSE SECE
  • 28. Returning a List from a Function list1 = [1, 2, 3, 4, 5, 6] list2 = reverse(list1) 28 def reverse(list): result = [] for element in list: result.insert(0, element) return result list result Note that list already has the reverse method list.reverse() ARULKUMAR V Ap/CSE SECE
  • 29. Problem: Counting Occurrence of Each Letter • Generate 100 lowercase letters randomly and assign to a list of characters. • Count the occurrence of each letter in the list. 29 CountLettersInList Run … … chars[0] chars[1] … … chars[98] chars[99] … … counts[0] counts[1] … … counts[24] counts[25] ARULKUMAR V Ap/CSE SECE
  • 30. Searching Lists Searching is the process of looking for a specific element in a list; for example, discovering whether a certain score is included in a list of scores. Searching is a common task in computer programming. There are many algorithms and data structures devoted to searching. In this section, two commonly used approaches are discussed, linear search and binary search. 30 # The function for finding a key in the list def linearSearch(lst, key): for i in range(0, len(lst)): if key == lst[i]: return i return -1 lst key Compare key with lst[i] for i = 0, 1, … [0] [1] [2] … ARULKUMAR V Ap/CSE SECE
  • 31. Linear Search The linear search approach compares the key element, key, sequentially with each element in list. The method continues to do so until the key matches an element in the list or the list is exhausted without a match being found. If a match is made, the linear search returns the index of the element in the list that matches the key. If no match is found, the search returns -1. 31ARULKUMAR V Ap/CSE SECE
  • 32. Linear Search Animation 32 6 4 1 9 7 3 2 8 6 4 1 9 7 3 2 8 6 4 1 9 7 3 2 8 6 4 1 9 7 3 2 8 6 4 1 9 7 3 2 8 6 4 1 9 7 3 2 8 3 3 3 3 3 3 animation Key List
  • 33. Linear Search Animation http://www.cs.armstrong.edu/liang/animation/LinearSea rchAnimation.html 33 animation Run ARULKUMAR V Ap/CSE SECE
  • 34. Binary Search For binary search to work, the elements in the list must already be ordered. Without loss of generality, assume that the list is in ascending order. e.g., 2 4 7 10 11 45 50 59 60 66 69 70 79 The binary search first compares the key with the element in the middle of the list. 34ARULKUMAR V Ap/CSE SECE
  • 35. Binary Search, cont. • If the key is less than the middle element, you only need to search the key in the first half of the list. • If the key is equal to the middle element, the search ends with a match. • If the key is greater than the middle element, you only need to search the key in the second half of the list. 35 Consider the following three cases: ARULKUMAR V Ap/CSE SECE
  • 36. Binary Search 36 1 2 3 4 6 7 8 9 1 2 3 4 6 7 8 9 1 2 3 4 6 7 8 9 8 8 8 Key List animation ARULKUMAR V Ap/CSE SECE
  • 37. Binary Search Animation http://www.cs.armstrong.edu/liang/animation/BinarySea rchAnimation.html 37 animation Run ARULKUMAR V Ap/CSE SECE
  • 38. Binary Search, cont. 38 [0] [1] [2] [3] [4] [5] [6] [7] [8] [9] [10] [11] [12] 2 4 7 10 11 45 50 59 60 66 69 70 79 key is 11 key < 50 lst mid [0] [1] [2] [3] [4] [5] key > 7 key == 11 highlow mid highlow lst [3] [4] [5] mid highlow lst 2 4 7 10 11 45 10 11 45 ARULKUMAR V Ap/CSE SECE
  • 39. Binary Search, cont. 39 [0] [1] [2] [3] [4] [5] [6] [7] [8] [9] [10] [11] [12] 2 4 7 10 11 45 50 59 60 66 69 70 79 key is 54 key > 50 lst mid [0] [1] [2] [3] [4] [5] [6] [7] [8] [9] [10] [11] [12] key < 66 key < 59 highlow mid highlow lst [7] [8] mid highlow lst 59 60 66 69 70 79 59 60 [6] [7] [8] highlow 59 60 ARULKUMAR V Ap/CSE SECE
  • 40. Binary Search, cont. The binarySearch method returns the index of the element in the list that matches the search key if it is contained in the list. Otherwise, it returns -insertion point - 1. The insertion point is the point at which the key would be inserted into the list. 40ARULKUMAR V Ap/CSE SECE
  • 41. From Idea to Soluton # Use binary search to find the key in the list def binarySearch(lst, key): low = 0 high = len(lst) - 1 while high >= low: mid = (low + high) // 2 if key < lst[mid]: high = mid - 1 elif key == lst[mid]: return mid else: low = mid + 1 return –low - 1 # Now high < low, key not found 41ARULKUMAR V Ap/CSE SECE
  • 42. Sorting Lists Sorting, like searching, is also a common task in computer programming. Many different algorithms have been developed for sorting. This section introduces two simple, intuitive sorting algorithms: selection sort and insertion sort. 42ARULKUMAR V Ap/CSE SECE
  • 43. Selection Sort Selection sort finds the largest number in the list and places it last. It then finds the largest number remaining and places it next to last, and so on until the list contains only a single number. Figure 6.17 shows how to sort the list {2, 9, 5, 4, 8, 1, 6} using selection sort. 43 2 9 5 4 8 1 6 swap Select 1 (the smallest) and swap it with 2 (the first) in the list 1 9 5 4 8 2 6 swap The number 1 is now in the correct position and thus no longer needs to be considered. 1 2 5 4 8 9 6 swap 1 2 4 5 8 9 6 Select 2 (the smallest) and swap it with 9 (the first) in the remaining list The number 2 is now in the correct position and thus no longer needs to be considered. Select 4 (the smallest) and swap it with 5 (the first) in the remaining list The number 6 is now in the correct position and thus no longer needs to be considered. 1 2 4 5 8 9 6Select 6 (the smallest) and swap it with 8 (the first) in the remaining list 1 2 4 5 6 9 8 swap The number 6 is now in the correct position and thus no longer needs to be considered. 1 2 4 5 6 8 9 Select 8 (the smallest) and swap it with 9 (the first) in the remaining list The number 8 is now in the correct position and thus no longer needs to be considered. Since there is only one element remaining in the list, sort is completed 5 is the smallest and in the right position. No swap is necessary The number 5 is now in the correct position and thus no longer needs to be considered. swap ARULKUMAR V Ap/CSE SECE
  • 44. Selection Sort Animation http://www.cs.armstrong.edu/liang/animation/Selection SortAnimation.html 44 animation Run ARULKUMAR V Ap/CSE SECE
  • 45. From Idea to Solution 45 for i in range(0, len(lst)): select the smallest element in lst[i.. len(lst)-1] swap the smallest with lst[i], if necessary # lst[i] is in its correct position. # The next iteration apply on lst[i+1..len(lst)-1] lst[0] lst[1] lst[2] lst[3] ... lst[10] lst[0] lst[1] lst[2] lst[3] ... lst[10] lst[0] lst[1] lst[2] lst[3] ... lst[10] lst[0] lst[1] lst[2] lst[3] ... lst[10] lst[0] lst[1] lst[2] lst[3] ... lst[10] ... lst[0] lst[1] lst[2] lst[3] ... lst[10] ARULKUMAR V Ap/CSE SECE
  • 46. Expand 46 for i in range(0, len(lst)): select the smallest element in lst[i.. len(lst)-1] swap the smallest with lst[i], if necessary # lst[i] is in its correct position. # The next iteration apply on lst[i+1..len(lst)-1] currentMin = lst[i] currentMinIndex = i for j in range(i + 1, len(lst)): if currentMin > lst[j]: currentMin = lst[j] currentMinIndex = j ARULKUMAR V Ap/CSE SECE
  • 47. Expand 47 for i in range(0, len(lst)): select the smallest element in lst[i.. len(lst)-1] swap the smallest with lst[i], if necessary # lst[i] is in its correct position. # The next iteration apply on lst[i+1..len(lst)-1] # Find the minimum in the lst[i..len(lst)-1] currentMin = lst[i] currentMinIndex = i for j in range(i + 1, len(lst)): if currentMin > lst[j]: currentMin = lst[j] currentMinIndex = j # Swap lst[i] with lst[currentMinIndex] if necessary if currentMinIndex != i: lst[currentMinIndex] = lst[i] lst[i] = currentMin ARULKUMAR V Ap/CSE SECE
  • 48. Wrap it in a Function 48 # The function for sorting the numbers def selectionSort(lst): for i in range(0, len(lst) - 1): # Find the minimum in the lst[i..len(lst)-1] currentMin = lst[i] currentMinIndex = i for j in range(i + 1, len(lst)): if currentMin > lst[j]: currentMin = lst[j] currentMinIndex = j # Swap lst[i] with lst[currentMinIndex] if necessary if currentMinIndex != i: lst[currentMinIndex] = lst[i] lst[i] = currentMin Invoke it selectionSort(yourList) ARULKUMAR V Ap/CSE SECE
  • 49. Insertion Sort myList = [2, 9, 5, 4, 8, 1, 6] # Unsorted 49 The insertion sort algorithm sorts a list of values by repeatedly inserting an unsorted element into a sorted sublist until the whole list is sorted. 2 9 5 4 8 1 6Step 1: Initially, the sorted sublist contains the first element in the list. Insert 9 into the sublist. 2 9 5 4 8 1 6Step2: The sorted sublist is [2, 9]. Insert 5 into the sublist. 2 5 9 4 8 1 6Step 3: The sorted sublist is [2, 5, 9]. Insert 4 into the sublist. 2 4 5 9 8 1 6Step 4: The sorted sublist is [2, 4, 5, 9]. Insert 8 into the sublist. 2 4 5 8 9 1 6Step 5: The sorted sublist is [2, 4, 5, 8, 9]. Insert 1 into the sublist. 1 2 4 5 8 9 6Step 6: The sorted sublist is [1, 2, 4, 5, 8, 9]. Insert 6 into the sublist. 1 2 4 5 6 8 9Step 7: The entire list is now sorted ARULKUMAR V Ap/CSE SECE
  • 50. Insertion Sort Animation http://www.cs.armstrong.edu/liang/animation/Insertion SortAnimation.html 50 animation Run ARULKUMAR V Ap/CSE SECE
  • 51. Insertion Sort myList = [2, 9, 5, 4, 8, 1, 6] # Unsorted 51 2 9 5 4 8 1 6 2 9 5 4 8 1 6 2 5 9 4 8 1 6 2 4 5 8 9 1 6 1 2 4 5 8 9 6 2 4 5 9 8 1 6 1 2 4 5 6 8 9 animation ARULKUMAR V Ap/CSE SECE
  • 52. How to Insert? 52 The insertion sort algorithm sorts a list of values by repeatedly inserting an unsorted element into a sorted sublist until the whole list is sorted. [0] [1] [2] [3] [4] [5] [6] 2 5 9 4list Step 1: Save 4 to a temporary variable currentElement [0] [1] [2] [3] [4] [5] [6] 2 5 9list Step 2: Move list[2] to list[3] [0] [1] [2] [3] [4] [5] [6] 2 5 9list Step 3: Move list[1] to list[2] [0] [1] [2] [3] [4] [5] [6] 2 4 5 9list Step 4: Assign currentElement to list[1] ARULKUMAR V Ap/CSE SECE
  • 53. From Idea to Solution 53 for i in range(1, len(lst)): insert lst[i] into a sorted sublist lst[0..i-1] so that lst[0..i] is sorted. lst[0] lst[0] lst[1] lst[0] lst[1] lst[2] lst[0] lst[1] lst[2] lst[3] lst[0] lst[1] lst[2] lst[3] ... ARULKUMAR V Ap/CSE SECE
  • 54. From Idea to Solution 54 for i in range(1, len(lst)): insert lst[i] into a sorted sublist lst[0..i-1] so that lst[0..i] is sorted. InsertSort Expand k = i - 1 while k >= 0 and lst[k] > currentElement: lst[k + 1] = lst[k] k -= 1 # Insert the current element into lst[k + 1] lst[k + 1] = currentElement ARULKUMAR V Ap/CSE SECE
  • 55. Case Studies: Bouncing Balls 55 BouncingBalls Run Ball x: int y: int dx: int dy: int color: Color radius: int The x-, y-coordinates for the center of the ball. By default, it is (0, 0). dx and dy are the increment for (x, y). The color of the ball. The radius of the ball. ARULKUMAR V Ap/CSE SECE
Current LanguageEnglish
Español
Portugues
Français
Deutsche
© 2024 SlideShare from Scribd

装修网简装修精装饰家装厨房台面简装一般都有啥家装水电工程报价表明细小卫生间装修设计精装样板房装修124平装修多少钱公装公装茶叶店的装修设计spa美容装修装修房子放线39度简装景阳春多少钱办装修装饰资质dogman精装中式装修客厅摆件三全简装汤圆成都室内有什么好玩的合肥公装公司家装家具尺寸大全不二家装修公司家装3d模型二十四城装饰网址毛坯房简装出租上海旧房装修公司毛坯房简装一般多少钱拉萨汽车装饰装修装饰公司好精装房装潢成都家装工程上饶国昌装饰香港通过《维护国家安全条例》两大学生合买彩票中奖一人不认账让美丽中国“从细节出发”19岁小伙救下5人后溺亡 多方发声汪小菲曝离婚始末卫健委通报少年有偿捐血浆16次猝死单亲妈妈陷入热恋 14岁儿子报警雅江山火三名扑火人员牺牲系谣言手机成瘾是影响睡眠质量重要因素男子被猫抓伤后确诊“猫抓病”中国拥有亿元资产的家庭达13.3万户高校汽车撞人致3死16伤 司机系学生315晚会后胖东来又人满为患了男孩8年未见母亲被告知被遗忘张家界的山上“长”满了韩国人?倪萍分享减重40斤方法许家印被限制高消费网友洛杉矶偶遇贾玲何赛飞追着代拍打小米汽车超级工厂正式揭幕男子被流浪猫绊倒 投喂者赔24万沉迷短剧的人就像掉进了杀猪盘特朗普无法缴纳4.54亿美元罚金周杰伦一审败诉网易杨倩无缘巴黎奥运专访95后高颜值猪保姆德国打算提及普京时仅用姓名西双版纳热带植物园回应蜉蝣大爆发七年后宇文玥被薅头发捞上岸房客欠租失踪 房东直发愁“重生之我在北大当嫡校长”校方回应护栏损坏小学生课间坠楼当地回应沈阳致3死车祸车主疑毒驾事业单位女子向同事水杯投不明物质路边卖淀粉肠阿姨主动出示声明书黑马情侣提车了奥巴马现身唐宁街 黑色着装引猜测老人退休金被冒领16年 金额超20万张立群任西安交通大学校长王树国卸任西安交大校长 师生送别西藏招商引资投资者子女可当地高考胖东来员工每周单休无小长假兔狲“狲大娘”因病死亡外国人感慨凌晨的中国很安全恒大被罚41.75亿到底怎么缴考生莫言也上北大硕士复试名单了专家建议不必谈骨泥色变“开封王婆”爆火:促成四五十对测试车高速逃费 小米:已补缴天水麻辣烫把捣辣椒大爷累坏了

装修网 XML地图 TXT地图 虚拟主机 SEO 网站制作 网站优化