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

Lesson 18 - List Comprehensions and List Assignments: Copying Lists

This document discusses list comprehensions in Python. It explains that changing an element in one list does not change another list that was created by calling list() on the first list. It also notes that for a list of lists, changing an inner list element will change it in both lists since the inner lists are referenced not copied. The document provides examples of using list comprehensions with range(), if statements, and to transform existing lists in various ways.

Uploaded by

raasiboi
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
32 views

Lesson 18 - List Comprehensions and List Assignments: Copying Lists

This document discusses list comprehensions in Python. It explains that changing an element in one list does not change another list that was created by calling list() on the first list. It also notes that for a list of lists, changing an inner list element will change it in both lists since the inner lists are referenced not copied. The document provides examples of using list comprehensions with range(), if statements, and to transform existing lists in various ways.

Uploaded by

raasiboi
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 2

Lesson 18 List comprehensions

and List assignments


Copying Lists
List 1 = [10,20,30,40]
List2 = list(list1)
List1[0] = 5
List1 = [5,20,30,40]

change made in list1

List2 = [10,20,30,40]

change in list1 does NOT cause change in list2

What about a list of lists?


List1 = [[10, 20] , [30, 40]]
List2 = list(list1)
List1[0][0] = 5
[[5, 20] , [30, 40]]
List2
[[5, 20] , [30,40]]\

Stingy OS
B = (list(A))
-

List 2 will contain a new list, but inner lists will be references not values

What do we do?
Append the lists

List comprehensions
Range() generates sequences of integers in fixed increments
List comprehension can be used to generate more varied sequences

List comprehension Syntax


L = [f(x) for x in S] Generate a list L

Loop over every X in S


Append f(x) to L
S = [1,2,3]
f(x) = x2

S = [1, 4, 9]

More powers! Combine with range()


[x**2 for x in range(10)]
[0,1,4,9,16,25,36,49,64,81]
Take in List L = [5,3,2,..]
And return L2 with every element in L multiplied by 5
List 2 = [25, 15, 10,..]
L2 = [x*5 for x in L]

More fun! Combine with if statements!


[ f(x) for x in S if condition ]
Nums = [-1, 0, 1, 2, -8, 4]
[ x for x in Nums if x >=0 ]
[1,2,4]
Vowels = ( a, e, I. o,u)
My_Word = hello
[x for x in My_word if x in Vowels]
[ e, o ]

You might also like