Lists

Iterate lists

l = [4, 9, 5, 7, 0]

for i in l:
	print(i)

Generate lists

Suppose we want to double the elements from the previous list.

l = [4, 9, 5, 7, 0]
new_list = []

for i in l:
	new_list += [i*2]

That was the long version. Better is:

l = [4, 9, 5, 7, 0]
new_list = [i*2 for i in l]

We want now to get the elements bigger than 5 and get their squared value.

l = [4, 9, 5, 7, 0]
new_list = []
for i in l:
	if i>5:
		new_list += [i**2]

The result is [81, 49].

We can also write this shorter:

l = [4, 9, 5, 7, 0]
new_list = [i**2 for i in l if i>5]

Update list elements

Recall how updating an element works:

l = [1, 2, 3, 2, 1]
l[2] = 5
print(l)	# [1, 2, 5, 2, 1]

This is called update by index. We knew the index of the element we wanted to update. If we want to update by value, we can iterate through the list and change the wanted element.

l = [1, 2, 3, 2, 1]
for i in l:
	new_list += [i*2]

Reversing a list

There are times when you need to reverse a list. Remember that you can do this very easy in python.

l = [1, 2, 3, 4, 5]
l = l[::-1]
print(l) # [5, 4, 3, 2, 1]

Delete from a list

A simple way to delete from a list is to filter through the elements. Let’s remove the 1s:

l = [1, 2, 3, 2, 1]
l = [i for i in l if i!=1]
print(l) # [2, 3, 2]

To remove just the first occurence, you can use .remove method:

l = [1, 2, 3, 2, 1]
l.remove(1)
print(l) # [2, 3, 2, 1]