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

Py 6

Lists allow us to store multiple values in a single variable. They are ordered collections that can contain any Python object and can be modified after creation. Common list operations include accessing elements by index, slicing lists, adding and removing elements, checking if an element is in the list, sorting lists, and using built-in functions like len(), max(), min() and sum() that take lists as parameters. Lists have many useful methods like append(), sort(), and split() which can break a string into a list of substrings.

Uploaded by

Mpi
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)
12 views

Py 6

Lists allow us to store multiple values in a single variable. They are ordered collections that can contain any Python object and can be modified after creation. Common list operations include accessing elements by index, slicing lists, adding and removing elements, checking if an element is in the list, sorting lists, and using built-in functions like len(), max(), min() and sum() that take lists as parameters. Lists have many useful methods like append(), sort(), and split() which can break a string into a list of substrings.

Uploaded by

Mpi
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/ 23

Python Lists

Lecture_6
A List is a 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' ]

carryon = [ 'socks', 'shirt', 'perfume'


]
What is not a “Collection”
• Most of our variables have one value in them - when we put a new
value in the variable - the old value is over written
$ python
Python 2.5.2 (r252:60911, Feb 22 2008, 07:57:53)
[GCC 4.0.1 (Apple Computer, Inc. build 5363)] on
darwin
>>> x = 2
>>> x = 4
>>> print x
4
List Constants
• List constants are surrounded by >>> print [1, 24, 76]
square brakets and the elements [1, 24, 76]
in the list are separated by >>> print ['red', 'yellow', 'blue']
commas. ['red', 'yellow', 'blue']
>>> print ['red', 24, 98.6]
['red', 24,
• A list element can be any Python 98.599999999999994]
object - even another list >>> print [ 1, [5, 6], 7]
[1, [5, 6], 7]
• A list can be empty >>> print []
[]
We already use lists!

5
for i in [5, 4, 3, 2, 1] : 4
print i 3
print ‘Hello!' 2
1
Hello!
Lists and definite loops - best pals

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


for friend in friends :
print 'Happy New Year:', Happy New Year: Joseph
friend Happy New Year: Glenn
print 'Done!' Happy New Year: Sally
Done!
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'


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

>>> greet = 'Hello Bob’


• The len() function takes a list as a >>> print len(greet)
parameter and returns the 9
number of elements in the list >>> x = [ 1, 2, 'joe', 99]
>>> print len(x)
• Actually len() tells us the number 4
of elements of any set or >>>
sequence (i.e. such as a string...)
Using the range function
>>> print range(4)
[0, 1, 2, 3]
• The range function returns a list >>> friends = ['Joseph', 'Glenn',
of numbers that range from zero 'Sally']
to one less than the parameter >>> print len(friends)
3
• We can construct an index loop >>> print range(len(friends))
using for and an integer iterator [0, 1, 2]
>>>
A tale of two loops...
>>> friends = ['Joseph', 'Glenn',
friends = ['Joseph', 'Glenn', 'Sally'] 'Sally']
>>> print len(friends)
for friend in friends : 3
print 'Happy New Year:', >>> print range(len(friends))
friend [0, 1, 2]
>>>
for i in range(len(friends)) : Happy New Year:
friend = friends[i] Joseph
print 'Happy New Year:', Happy New Year:
friend Glenn
Happy New Year: Sally
Concatenating lists using +
>>> a = [1, 2,
3]
>>> b = [4, 5,
6]
• We can create a new list by adding >>> c = a + b
two exsiting lists together >>> print c
[1, 2, 3, 4, 5, 6]
>>> print a
[1, 2, 3]
Lists can be sliced using :
>>> t = [9, 41, 12, 3, 74,
15]
>>> t[1:3] Remember: Just like in
[41,12] strings, the second
>>> t[:4] number is "up to but not
[9, 41, 12, 3] 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']
>>>
Building a list from scratch

>>> stuff = list()


• We can create an empty >>> stuff.append('book')
list and then add elements
>>> stuff.append(99)
using the append method
>>> print stuff
['book', 99]
• The list stays in order and >>> stuff.append('cookie')
new elements are added at >>> print stuff
the end of the list ['book', 99, 'cookie']
Is Something in a List?
• Python provides two
operators that let you >>> some = [1, 9, 21, 10,
check if an item is in a list 16]
>>> 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
A List is an Ordered Sequence
• A list can hold many items
and keeps those items in the >>> friends = [ 'Joseph', 'Glenn', 'Sally'
order until we do something ]
to change the order >>> friends.sort()
>>> print friends
• A list can be sorted (i.e. ['Glenn', 'Joseph', 'Sally']
>>> print friends[1]
change its order)
Joseph>>>
• The sort method (unlike in
strings) means "sort yourself"
Built in Functions and Lists
>>> nums = [3, 41, 12, 9, 74,
15]
• There are a number of >>> print len(nums)
functions built into Python 6
that take lists as >>> 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
Enter a number: 3
total = 0
count = 0 Enter a number: 9
while True : Enter a number: 5
inp = input('Enter a number: ')
if inp == 'done' : break Enter a number: done
value = float(inp)
total = total + value
Average: 5.66666666667
count = count + 1

average = total / count


print 'Average:', average
numlist = list()
while True :
inp = input('Enter a number: ')
if inp == 'done' : break
value = float(inp)
numlist.append(value)

average = sum(numlist) / len(numlist)


print 'Average:', average
Best Friends: Strings and Lists
>>> print stuff
>>> abc = 'With three words’
['With', 'three',
>>> stuff = abc.split()
'words']
>>> print stuff >>> for w in stuff :
['With', 'three', 'words']
... print w
>>> print len(stuff)
...
3 With
>>> print stuff[0] Three
With
Words
>>>
Split breaks a string into parts produces a list of strings. We think of these as
words. We can access a particular word or loop through all the words.
>>> line = 'A lot of spaces’
>>> etc = line.split()
>>> print etc['A', 'lot', 'of', 'spaces']
>>>
>>> line = 'first;second;third’
>>> thing = line.split()
>>> print thing['first;second;third']
>>> print len(thing)
1
>>> thing = line.split(';')
>>> print thing['first', 'second', 'third']
>>> print len(thing)
3 When you do not specify a delimiter, multiple
>>>
spaces are treated like “one” delimiter.

You can specify what delimiter character to


use in the splitting.
List Summary
• Concept of a collection
• Lists and definite loops
• Indexing and lookup
• List mutability
Questions

You might also like

pFad - Phonifier reborn

Pfad - The Proxy pFad of © 2024 Garber Painting. All rights reserved.

Note: This service is not intended for secure transactions such as banking, social media, email, or purchasing. Use at your own risk. We assume no liability whatsoever for broken pages.


Alternative Proxies:

Alternative Proxy

pFad Proxy

pFad v3 Proxy

pFad v4 Proxy