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

Pythonlearn 08 Lists

This document discusses lists in Python. It defines lists as a data structure that allows storing multiple values in a single variable. Lists are defined using square brackets and elements within a list are separated by commas. Lists are mutable, meaning the elements within a list can be changed. Some key list functions and operations discussed include accessing elements by index, finding the length of a list using len(), concatenating lists with +, and slicing lists using index ranges. Loops can be used to iterate over lists.

Uploaded by

Hưng Minh Phan
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)
15 views

Pythonlearn 08 Lists

This document discusses lists in Python. It defines lists as a data structure that allows storing multiple values in a single variable. Lists are defined using square brackets and elements within a list are separated by commas. Lists are mutable, meaning the elements within a list can be changed. Some key list functions and operations discussed include accessing elements by index, finding the length of a list using len(), concatenating lists with +, and slicing lists using index ranges. Loops can be used to iterate over lists.

Uploaded by

Hưng Minh Phan
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/ 8

10/01/21

Programming
• Algorithm

Python Lists - A set of rules or steps used to solve a problem

Chapter 8 • Data Structure


- A particular way of organizing data in a computer

Python for Everybody


https://en.wikipedia.org/wiki/Algorithm
www.py4e.com
https://en.wikipedia.org/wiki/Data_structure

1 2

A List is a Kind of
What is Not a “Collection”?
Collection
Most of our variables have one value in them - when we put a new • A collection allows us to put many values in a single “variable”
value in the variable, the old value is overwritten
• A collection is nice because we can carry all many values
around in one convenient package.
$ python
>>> x = 2
>>> x = 4 friends = [ 'Joseph', 'Glenn', 'Sally' ]
>>> print(x)
4 carryon = [ 'socks', 'shirt', 'perfume' ]

3 4
10/01/21

List Constants We Already Use Lists!


• List constants are surrounded by >>> print([1, 24, 76])
square brackets and the elements [1, 24, 76]
>>> print(['red', 'yellow',
5
in the list are separated by for i in [5, 4, 3, 2, 1] :
commas
'blue'])
print(i) 4
['red', 'yellow', 'blue']
>>> print(['red', 24, 98.6]) print('Blastoff!') 3
• A list element can be any Python ['red', 24, 98.6]
>>> print([ 1, [5, 6], 7])
2
object - even another list [1, [5, 6], 7] 1
>>> print([])
• A list can be empty [] Blastoff!

5 6

Lists and Definite Loops - Best Pals Looking Inside Lists

friends = ['Joseph', 'Glenn', 'Sally'] Just like strings, we can get at any single element in a list using an
for friend in friends :
print('Happy New Year:', friend)
Happy New Year: Joseph index specified in square brackets
print('Done!') Happy New Year: Glenn
Happy New Year: Sally
>>> friends = [ 'Joseph', 'Glenn', 'Sally' ]
Done! Joseph Glenn Sally >>> print(friends[1])
z = ['Joseph', 'Glenn', 'Sally'] Glenn
for x in z: 0 1 2 >>>
print('Happy New Year:', x)
print('Done!')

7 8
10/01/21

Lists are Mutable How Long is a List?


>>> fruit = 'Banana'
>>> fruit[0] = 'b'
• Strings are “immutable” - we Traceback
cannot change the contents of a TypeError: 'str' object does not • The len() function takes a list as a >>> greet = 'Hello Bob'
string - we must make a new string support item assignment parameter and returns the number >>> print(len(greet))
>>> x = fruit.lower()
to make any change >>> print(x) of elements in the list 9
banana >>> x = [ 1, 2, 'joe', 99]
>>> lotto = [2, 14, 26, 41, 63] >>> print(len(x))
• Lists are “mutable” - we can >>> print(lotto) • Actually len() tells us the number of 4
change an element of a list using [2, 14, 26, 41, 63] elements of any set or sequence >>>
>>> lotto[2] = 28
the index operator >>> print(lotto) (such as a string...)
[2, 14, 28, 41, 63]

9 10

Using the range Function A Tale of Two Loops...


>>> friends = ['Joseph', 'Glenn', 'Sally']
• The range function returns friends = ['Joseph', 'Glenn', 'Sally'] >>> print(len(friends))
>>> print(range(4)) 3
a list of numbers that range [0, 1, 2, 3] for friend in friends : >>> print(range(len(friends)))
from zero to one less than >>> friends = ['Joseph', 'Glenn', 'Sally'] print('Happy New Year:', friend) [0, 1, 2]
>>> print(len(friends)) >>>
the parameter 3 for i in range(len(friends)) :
>>> print(range(len(friends))) friend = friends[i]
[0, 1, 2]
• We can construct an index >>>
print('Happy New Year:', friend) Happy New Year: Joseph
loop using for and an Happy New Year: Glenn
integer iterator Happy New Year: Sally

11 12
10/01/21

Concatenating Lists Using + Lists Can Be Sliced Using :


>>> a = [1, 2, 3]
>>> t = [9, 41, 12, 3, 74, 15]
We can create a new list >>> b = [4, 5, 6]
>>> c = a + b >>> t[1:3]
by adding two existing [41,12] Remember: Just like in
>>> print(c)
lists together >>> t[:4] strings, the second
[1, 2, 3, 4, 5, 6]
[9, 41, 12, 3] number is “up to but not
>>> print(a)
>>> t[3:]
[1, 2, 3] including”
[3, 74, 15]
>>> t[:]
[9, 41, 12, 3, 74, 15]

13 14

List Methods Building a List from Scratch


>>> x = list()
>>> type(x) >>> stuff = list()
• We can create an empty list >>> stuff.append('book')
<type 'list'>
and then add elements using >>> stuff.append(99)
>>> dir(x)
['append', 'count', 'extend', 'index', 'insert', the append method >>> print(stuff)
'pop', 'remove', 'reverse', 'sort'] ['book', 99]
• The list stays in order and >>> stuff.append('cookie')
>>>
>>> print(stuff)
new elements are added at
['book', 99, 'cookie']
the end of the list
http://docs.python.org/tutorial/datastructures.html

15 16
10/01/21

Is Something in a List? Lists are in Order


• A list can hold many
items and keeps
• Python provides two operators >>> some = [1, 9, 21, 10, 16] those items in the
that let you check if an item is >>> 9 in some order until we do >>> friends = [ 'Joseph', 'Glenn', 'Sally' ]
True >>> friends.sort()
in a list something to change >>> print(friends)
>>> 15 in some
False the order ['Glenn', 'Joseph', 'Sally']
• These are logical operators >>> print(friends[1])
>>> 20 not in some • A list can be sorted Joseph
that return True or False True >>>
(i.e., change its order)
>>>
• They do not modify the list • The sort method
(unlike in strings)
means “sort yourself”

17 18

total = 0 Enter a number: 3


Built-in Functions and Lists count = 0
while True :
Enter a number: 9
inp = input('Enter a number: ') Enter a number: 5
>>> nums = [3, 41, 12, 9, 74, 15] if inp == 'done' : break
• There are a number of value = float(inp) Enter a number: done
>>> print(len(nums))
functions built into Python 6
total = total + value Average: 5.66666666667
count = count + 1
that take lists as >>> print(max(nums))
parameters 74 average = total / count
numlist = list()
>>> print(min(nums)) print('Average:', average)
while True :
3
• Remember the loops we >>> print(sum(nums))
inp = input('Enter a number: ')
if inp == 'done' : break
built? These are much 154 value = float(inp)
simpler. >>> print(sum(nums)/len(nums)) numlist.append(value)
25.6
average = sum(numlist) / len(numlist)
print('Average:', average)

19 20
10/01/21

Best Friends: Strings and Lists


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

21 22

From [email protected] Sat Jan 5 09:14:16 2008


The Double Split Pattern
fhand = open('mbox-short.txt') Sat
for line in fhand:
Fri
Sometimes we split a line one way, and then grab one of the pieces
line = line.rstrip()
if not line.startswith('From ') : continue Fri of the line and split that piece again
words = line.split()
print(words[2]) Fri
... From [email protected] Sat Jan 5 09:14:16 2008

words = line.split()
email = words[1]
>>> line = 'From [email protected] Sat Jan 5 09:14:16 2008' print pieces[1]
>>> words = line.split()
>>> print(words)
['From', '[email protected]', 'Sat', 'Jan', '5', '09:14:16', '2008']
>>>

23 24
10/01/21

The Double Split Pattern The Double Split Pattern

From [email protected] Sat Jan 5 09:14:16 2008 From [email protected] Sat Jan 5 09:14:16 2008

words = line.split() words = line.split()


email = words[1] [email protected] email = words[1] [email protected]
print pieces[1] pieces = email.split('@') ['stephen.marquard', 'uct.ac.za']
print pieces[1]

25 26

The Double Split Pattern List Summary


• Concept of a collection • Slicing lists

• Lists and definite loops • List methods: append, remove


From [email protected] Sat Jan 5 09:14:16 2008
• Indexing and lookup • Sorting lists
words = line.split()
email = words[1] [email protected] • List mutability • Splitting strings into lists of words
pieces = email.split('@') ['stephen.marquard', 'uct.ac.za']
print(pieces[1]) 'uct.ac.za' • Functions: len, min, max, sum • Using split to parse strings

27 28
10/01/21

Acknowledgements / Contributions
These slides are Copyright 2010- Charles R. Severance
...
(www.dr-chuck.com) of the University of Michigan School of
Information and open.umich.edu and made available under a
Creative Commons Attribution 4.0 License. Please maintain this
last slide in all copies of the document to comply with the
attribution requirements of the license. If you make a change,
feel free to add your name and organization to the list of
contributors on this page as you republish the materials.

Initial Development: Charles Severance, University of Michigan


School of Information

… Insert new Contributors and Translators here

29

You might also like