0% found this document useful (0 votes)
16 views

5 Python5 Lists

lists

Uploaded by

sabakabha
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)
16 views

5 Python5 Lists

lists

Uploaded by

sabakabha
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/ 37

Python Lists

Python Collections (Arrays)


There are four collection data types in the Python programming language:

List is a collection which is ordered and changeable. Allows duplicate


members.
Tuple is a collection which is ordered and unchangeable. Allows duplicate
members.
Set is a collection which is unordered and unindexed. No duplicate
members.
Dictionary is a collection which is ordered* and changeable. No duplicate
members.

When choosing a collection type, it is useful to understand the


properties of that type. Choosing the right type for a particular data set
could mean retention of meaning, and, it could mean an increase in
efficiency or security.
Outline
• Lists
• Indexing and lookup
• Lists and loops
• Slicing lists
• List mutability
• List methods: append, remove, sort..
• Functions: len, min, max, sum
A List is kind of Collection
A collection allows us to put many values in a single “variable”

A collection is nice because we can carry all many values around in


one convenient package.

friends = [ 'Joseph', 'Glenn', 'Sally' ]


cars= [ 'Toyota', 'BMW', 'Volvo' ]
list1 = [1, 5, 7, 9, 3]
list2 = [True, False, False]
Creating a List
List Constants
• List constants are surrounded
by square brakets and the >>> print [1, 24, 76]
elements in the list are [1, 24, 76]
separated by commas. >>> print ['red', 'yellow', 'blue']
['red', 'yellow', 'blue']
• A list element can be any >>> print ['red', 24, 98.6]
Python object - even another ['red', 24, 98.599999999999994]
list >>> print [ 1, [5, 6], 7]
[1, [5, 6], 7]
>>> print []
• A list can be empty []
Looking Inside Lists

• Just like strings, we can get at any single element in a list using an
index specified in square brackets

>>> friends = [ 'Joseph', 'Glenn', 'Sally' ]


>>> print friends[1]
Glenn
>>>
Looking Inside Lists

• We can get at any single element even in case of nested lists

>>> t= [ 1, [5, 6], 7]


>>> print (t[ 1 ])
[5, 6]

>>> print (t[ 1 ][ 0 ])


5
Lists and WhileLoops

friends = ['Ali', 'Ahmad', 'Sally']


i=0
while i< 3 : Happy New Year: Ali
print('Happy New Year:', friends[i])
i=i+1 Happy New Year: Ahmad
print('Done!') Happy New Year: Sally
Done!
Lists and for Loops

friends = ['Ali', 'Ahmad', 'Sally']


for f in friends : Happy New Year: Ali
print('Happy New Year:', friend)
print('Done!') Happy New Year: Ahmad
Happy New Year: Sally
Done!
Lists are Mutable >>> fruit = 'Banana’
>>> fruit[0] = 'b’
Traceback
• Strings are "immutable" - TypeError: 'str' object does not
we cannot change the support item assignment
contents of a string - we >>> x = fruit.lower()
must make a new string to >>> print x
make any change banana
>>> lotto = [2, 14, 26, 41, 63]
• Lists are "mutable" - we >>> print lotto
can change an element of a [2, 14, 26, 41, 63]
list using the index >>> lotto[2] = 28
operator >>> print lotto
[2, 14, 28, 41, 63]
How Long is a List?

• The len() function takes a list


>>> greet = 'Hello Bob’
as a parameter and returns the
>>> print len(greet)
number of elements in the list
9
>>> x = [ 1, 2, 'joe', 99]
• Actually len() tells us the >>> print len(x)
number of elements of any set 4
or sequence (i.e. such as a >>>
string...)
Using the range function
>>> print(list(range(4)))
• The range function returns a [0, 1, 2, 3]
list of numbers that range >>> friends = ['Joseph', 'Glenn', 'Sally']
from zero to one less than >>> print len(friends)
the parameter 3
>>> print(list(range(len(friends)))
[0, 1, 2]
>>>
Lists can be sliced using :

>>> t = [9, 41, 12, 3, 74, 15]


>>> t[1:3]
[41,12] Remember: Just like in
>>> t[:4] strings, the second number
[9, 41, 12, 3] is "up to but not including"
>>> t[3:]
[3, 74, 15]
>>> t[:]
[9, 41, 12, 3, 74, 15]
List Methods

>>> x = list()
>>> type(x)
<type 'list'>
>>> dir(x)
['append', 'count', 'extend', 'index', 'insert',
'pop', 'remove', 'reverse', 'sort']
>>>

http://docs.python.org/tutorial/datastructures.html
Building a list from scratch

• We can create an
empty list and then add >>> stuff = list()
elements using the >>> stuff.append('book')
append method >>> stuff.append(99)
>>> print (stuff)
• The list stays in order
['book', 99]
>>> stuff.append('cookie')
and new elements are
>>> print (stuff)
added at the end of the
['book', 99, 'cookie']
list
A List is an Ordered Sequence

• A list can hold many


items and keeps those
items in the order until >>> friends = [ 'Joseph', 'Glenn', 'Sally' ]
we do something to >>> friends.sort()
change the order >>> print friends
['Glenn', 'Joseph', 'Sally']
• A list can be sorted (i.e. >>> print friends[1]
Joseph
change its order)
List Methods

list=["a","b","c","d","c"]
list.index("c",3)
Lists Operators

+ : Concatenation
* : Repetition
in : Membership
Note: - and / are not supported for lists
Concatenating lists using +

>>> a = [1, 2, 3]
>>> b = [4, 5, 6]
• We can create a new list by >>> c = a + b
adding two exsiting lists >>> print c
together [1, 2, 3, 4, 5, 6]
>>> print a
[1, 2, 3]
Repetition using *
>>> a = [1, 2, 3]
>>> n = 2
• We can repeate a list n times by >>> c = a * n
multiplying the list by n >>> print (c)
[1, 2, 3, 1, 2, 3]
• Allow Duplicates: Since lists are >>> print (a)
indexed, lists can have items with the [1, 2, 3]
same value

>>> a = [0]
>>> print (a*5)
[0, 0, 0, 0, 0]
Is Something in a List?
• Python provides two
operators that let you
check if an item is in a >>> some = [1, 9, 21, 10, 16]
list >>> 9 in some
True
• These are logical >>> 15 in some
operators that return False
True or False >>> 20 not in some
True
>>>
• They do not modify the
list
Built-in Functions and Lists

• There are a number of >>> nums = [3, 41, 12, 9, 74, 15]
functions built into >>> print(len(nums))
Python that take lists as 6
>>> print(max(nums))
parameters
74
>>> print(min(nums))
3
• Remember the loops we >>> print(sum(nums))
built? These are much 154
simpler. >>> print(sum(nums)/len(nums))
25.6
The list() Constructor
It is also possible to use the list() constructor when creating a new list.
list constructer takes only one argument thus the brackets
thislist = list(("apple", "banana", "cherry")) # note the double round-brackets
print(thislist)
>>> ['apple', 'banana', 'cherry']

Negative Indexing
Negative indexing means start from the end
-1 refers to the last item, -2 refers to the second last item etc.

thislist = ["apple", "banana", "cherry"]


print(thislist[-1])
>>> cherry

Range of Negative Indexes

thislist = ["apple", "banana", "cherry", "orange", "kiwi", "melon", "mango"]


print(thislist[-4:-1])
>>>['orange', 'kiwi', 'melon']
Change a Range of Item Values
thislist = ["apple", "banana", "cherry", "orange", "kiwi", "mango"]
thislist[1:3] = ["lemon", "watermelon"]
print(thislist)
>>> ['apple', 'lemon', 'watermelon', 'orange', 'kiwi', 'mango']

• If you insert more items than you replace, the new items will be inserted where
you specified, and the remaining items will move accordingly:

thislist = ["apple", "banana", "cherry"]


thislist[1:2] = ["lemont", "watermelon"]
print(thislist)
>>> ['apple', 'lemon', 'watermelon', 'cherry']

• If you insert less items than you replace, the new items will be inserted where
you specified, and the remaining items will move accordingly:
thislist = ["apple", "banana", "cherry"]
thislist[1:3] = ["watermelon"]
print(thislist)
>>>['apple', 'watermelon']
Append Items
To add an item to the end of the list, use the append() method:

thislist = ["apple", "banana", "cherry"]


thislist.append("orange")
print(thislist)
>>>['apple', 'banana', 'cherry', 'orange']

Insert Items
To insert a list item at a specified index, use the insert() method.
The insert() method inserts an item at the specified index:

thislist = ["apple", "banana", "cherry"]


thislist.insert(1, "orange")
print(thislist)
>>>['apple', 'orange', 'banana', 'cherry']

Extend List
To append elements from another list to the current list, use the extend() method.
thislist = ["apple", "banana", "cherry"]
tropical = ["mango", "pineapple", "papaya"]
thislist.extend(tropical)
print(thislist)
>>>['apple', 'banana', 'cherry', 'mango', 'pineapple', 'papaya']
Remove Specified Item
The remove() method removes the specified item.

thislist = ["apple", "banana", "cherry"]


thislist.remove("banana")
print(thislist)
>>> ['apple', 'cherry']

Remove Specified Index


The pop() method removes the specified index.

thislist = ["apple", "banana", "cherry"]


thislist.pop(1)
print(thislist)
>>> ['apple', 'cherry']

If you do not specify the index, the pop() method removes the last item.

thislist = ["apple", "banana", "cherry"]


thislist.pop()
print(thislist)
>>>['apple', 'banana']
Clear the List

The clear() method empties the list.


The list still remains, but it has no content.

thislist = ["apple", "banana", "cherry"]


thislist.clear()
print(thislist)
>>>[]
Looping Using List Comprehension

List Comprehension offers the shortest syntax for looping through lists:

thislist = ["apple", "banana", "cherry"]


[print(x) for x in thislist]
>>> apple
banana
Cherry

newlist = [expression for item in iterable if condition == True]

Examples:
• Based on a list of fruits, you want a new list, containing only the fruits with the
letter "a" in the name.
fruits = ["apple", "banana", "cherry", "kiwi", "mango"]
newlist = [x for x in fruits if "a" in x]
print(newlist)
>>>['apple', 'banana', 'mango']

• Set the values in the new list to upper case:


newlist = [x.upper() for x in fruits]
>>>['APPLE', 'BANANA', 'CHERRY', 'KIWI', 'MANGO']
Sort Descending
To sort descending, use the keyword argument reverse = True:

thislist = ["orange", "mango", "kiwi", "pineapple", "banana"]


thislist.sort(reverse = True)
print(thislist)
>>>['pineapple', 'orange', 'mango', 'kiwi', 'banana']

Customize Sort Function


You can also customize your own function by using the keyword argument key
= function. The function will return a number that will be used to sort the list (the lowest
number first):

def myfunc(n):
return abs(n - 50)

thislist = [100, 50, 65, 82, 23]


thislist.sort(key = myfunc)
print(thislist)

>>>[50, 65, 23, 82, 100]


Case Insensitive Sort
By default the sort() method is case sensitive, if you want a case-insensitive sort function,
use str.lower as a key function:

thislist = ["banana", "Orange", "Kiwi", "cherry"]


thislist.sort(key = str.lower)
print(thislist)
>>>['banana', 'cherry', 'Kiwi', 'Orange']

Reverse Order
What if you want to reverse the order of a list, regardless of the alphabet?

thislist = ["banana", "Orange", "Kiwi", "cherry"]


thislist.reverse()
print(thislist)
>>>['cherry', 'Kiwi', 'Orange', 'banana']
Copy a List
You cannot copy a list simply by typing list2 = list1, because: list2 will only be
a reference to list1, and changes made in list1 will automatically also be made in list2.

thislist = ["apple", "banana", "cherry"]


mylist = thislist.copy()
print(mylist)
>>> ['apple', 'banana', 'cherry']

Another way to make a copy is to use the built-in method list().


thislist = ["apple", "banana", "cherry"]
mylist = list(thislist)
print(mylist)
>>> ['apple', 'banana', 'cherry']

List index()
The index() method returns the position at the first occurrence of the specified value.

fruits = ['apple', 'banana', 'cherry']


x = fruits.index("cherry")
>>>2
List count()
The count() method returns the number of elements with the specified value.

points = [1, 4, 2, 9, 7, 8, 9, 3, 1]
x = points.count(9)
>>>2
List Summary
• Concept of a collection
• Lists and definite loops
• Indexing and lookup
• Slicing lists
• List mutability
• List methods: append, remove, sort..
• Functions: len, min, max, sum

You might also like