0% found this document useful (0 votes)
38 views13 pages

Understanding Python Lists and Collections

The document provides an overview of Python lists, explaining their characteristics as a mutable collection data type that can store multiple values. It covers various operations such as indexing, slicing, appending, inserting, and removing elements, as well as built-in functions that can be applied to lists. Additionally, it highlights the relationship between lists and strings, particularly the use of the split() method to create lists from strings.

Uploaded by

rayansharrofna
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)
38 views13 pages

Understanding Python Lists and Collections

The document provides an overview of Python lists, explaining their characteristics as a mutable collection data type that can store multiple values. It covers various operations such as indexing, slicing, appending, inserting, and removing elements, as well as built-in functions that can be applied to lists. Additionally, it highlights the relationship between lists and strings, particularly the use of the split() method to create lists from strings.

Uploaded by

rayansharrofna
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

08/11/2025

Python Lists

Python for Everybody


[Link]

Programming
• Algorithm
- A set of rules or steps used to solve a problem

• Data Structure
- A particular way of organizing data in a computer

1
08/11/2025

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 overwritten

$ python
>>> x = 2
>>> x = 4
>>> print(x)
4

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 unchangeable , and unindexed.
No duplicate members.
• Dictionary is a collection which is ordered and changeable. No duplicate
members.

2
08/11/2025

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' ]

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

3
08/11/2025

We Already Use Lists!


5
for i in [5, 4, 3, 2, 1] :
print(i) 4
print('Blastoff!') 3
2
1
Blastoff!

Lists and Definite Loops - Best Pals

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


for friend in friends : Happy New Year: Joseph
print('Happy New Year:', friend)
print('Done!') Happy New Year: Glenn
Happy New Year: Sally
Done!
z = ['Joseph', 'Glenn', 'Sally']
for x in z:
print('Happy New Year:', x)
print('Done!')

4
08/11/2025

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])
Glenn
0 1 2 >>>

Lists are Mutable


>>> fruit = 'Banana'
>>> fruit[0] = 'b'
• Strings are “immutable” - we Traceback
cannot change the contents of a TypeError: 'str' object does not
string - we must make a new string support item assignment
>>> x = [Link]()
to make any change >>> print(x)
banana
>>> lotto = [2, 14, 26, 41, 63]
• Lists are “mutable” - we can >>> print(lotto)
change an element of a list using [2, 14, 26, 41, 63]
>>> lotto[2] = 28
the index operator >>> print(lotto)
[2, 14, 28, 41, 63]

10

5
08/11/2025

How Long is a List?

• The len() function takes a list as a >>> greet = 'Hello Bob'


parameter and returns the number >>> print(len(greet))
of elements in the list 9
>>> x = [ 1, 2, 'joe', 99]
>>> print(len(x))
• Actually len() tells us the number of 4
elements of any set or sequence >>>
(such as a string, list...)

11

Using the range Function


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

12

6
08/11/2025

A Tale of Two Loops...


>>> friends = ['Joseph', 'Glenn', 'Sally']
friends = ['Joseph', 'Glenn', 'Sally'] >>> print(len(friends))
3
for friend in friends : >>> print(list(range(len(friends))))
print('Happy New Year:', friend) [0, 1, 2]
>>>
for i in range(len(friends)) :
friend = friends[i]
print('Happy New Year:', friend) Happy New Year: Joseph
Happy New Year: Glenn
Happy New Year: Sally

13

Concatenating Lists Using +


>>> a = [1, 2, 3]
We can create a new list >>> b = [4, 5, 6]
by adding two existing >>> c = a + b
>>> print(c)
lists together
[1, 2, 3, 4, 5, 6]
>>> print(a)
[1, 2, 3]

14

7
08/11/2025

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
[9, 41, 12, 3] number is “up to but not
>>> t[3:] including”
[3, 74, 15]
>>> t[:]
[9, 41, 12, 3, 74, 15]

15

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

[Link]

16

8
08/11/2025

Building a List from Scratch


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

17

Add Elements at the Specified Index


• We can insert an element at
the specified index to a list fruits = ['apple', 'banana', 'orange’]
using the insert() method. print("Original List:", fruits)

[Link](2, 'cherry')

Output print("Updated List:", fruits)


Original List: ['apple', 'banana', 'orange']

Updated List: ['apple', 'banana', 'cherry', 'orange']

18

9
08/11/2025

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

19

Lists are in Order


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

• The sort method


(unlike in strings)
means “sort yourself”

20

10
08/11/2025

Change List Items


colors = ['Red', 'Black', 'Green']
• We can change the items
print( 'Original List:', colors)
of a list by assigning new
values using # change the first item to 'Purple'
the = operator to a colors[0] = 'Purple'
specific index.
# change the third item to 'Blue'
colors[2] = 'Blue'
Output
Original List: ['Red', 'Black', 'Green'] print('Updated List:', colors)
Updated List: ['Purple', 'Black', 'Blue']

21

Remove an Item From a List


numbers = [2,4,7,9]
• We can remove the
specified item from a list # remove item indexed in 4
using the remove() method. from the list
[Link](4)

print(numbers)
Output
[2, 7, 9]

22

11
08/11/2025

Built-in Functions and Lists


>>> nums = [3, 41, 12, 9, 74, 15]
• There are a number of >>> print(len(nums))
functions built into Python that 6
take lists as parameters >>> print(max(nums))
len(), max(), min(), 74
sum() >>> print(min(nums))
3
>>> print(sum(nums))
• Remember the loops we built? 154
These are much simpler. >>> print(sum(nums)/len(nums))
25.6

23

Best Friends: Strings and Lists


>>> abc = 'With three words' >>> print(stuff)
>>> stuff = [Link]() ['With', 'three', '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 and produces a list of strings. We think of
these as words. We can access a particular word or loop through all the
words.

24

12
08/11/2025

List Summary
• Concept of a collection • Slicing lists

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


remove
• Indexing and lookup
• Sorting lists
• List mutability
• Split lists
• Functions: len, min, max, sum

25

Acknowledgements / Contributions
These slides are Copyright 2010- Charles R. Severance
...
([Link]) of the University of Michigan School of
Information and [Link] 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

… rt new Contributors and Translators here

26

13

You might also like