Manipulating Lists

Introduction to Python

Hugo Bowne-Anderson

Data Scientist at DataCamp

List Manipulation

  • Change list elements

  • Add list elements

  • Remove list elements

Introduction to Python

Changing list elements

fam = ["liz", 1.73, "emma", 1.68, "mom", 1.71, "dad", 1.89]
fam
['liz', 1.73, 'emma', 1.68, 'mom', 1.71, 'dad', 1.89]
fam[7] = 1.86
fam
['liz', 1.73, 'emma', 1.68, 'mom', 1.71, 'dad', 1.86]
fam[0:2] = ["lisa", 1.74]
fam
['lisa', 1.74, 'emma', 1.68, 'mom', 1.71, 'dad', 1.86]
Introduction to Python

Adding and removing elements

fam + ["me", 1.79]
['lisa', 1.74,'emma', 1.68, 'mom', 1.71, 'dad', 1.86, 'me', 1.79]
fam_ext = fam + ["me", 1.79]

del fam[2]
fam
['lisa', 1.74, 1.68, 'mom', 1.71, 'dad', 1.86]
Introduction to Python

Behind the scenes (1)

x = ["a", "b", "c"]

ch_2_3_slides.024.png

Introduction to Python

Behind the scenes (1)

x = ["a", "b", "c"]

y = x
y[1] = "z" y
['a', 'z', 'c']
x
['a', 'z', 'c']

ch_2_3_slides.025.png

Introduction to Python

Behind the scenes (1)

x = ["a", "b", "c"]

y = x
y[1] = "z" y
['a', 'z', 'c']
x
['a', 'z', 'c']

ch_2_3_slides.030.png

Introduction to Python

Behind the scenes (1)

x = ["a", "b", "c"]

y = x
y[1] = "z" y
['a', 'z', 'c']
x
['a', 'z', 'c']

ch_2_3_slides.031.png

Introduction to Python

Behind the scenes (2)

x = ["a", "b", "c"]

ch_2_3_slides.033.png

Introduction to Python

Behind the scenes (2)

x = ["a", "b", "c"]

y = list(x) y = x[:]

ch_2_3_slides.034.png

Introduction to Python

Behind the scenes (2)

x = ["a", "b", "c"]

y = list(x) y = x[:]
y[1] = "z" x
['a', 'b', 'c']

ch_2_3_slides.036.png

Introduction to Python

Let's practice!

Introduction to Python

Preparing Video For Download...