Python lists

Share me please

Creating lists in Python

[cc lang=”python”]
# creating and initializing lists
list = [ 1, 2, 3, 4]
print(list)
print(type(list))
[/cc]

How to index with python lists

[cc lang=”python” height=”410px”]
# indexing list and changing values
list = [ -1, 1, 1, 2, 3]
print(list)

# getting first element and changing its value
# (positive indexing starting from 0 at the beggining
print(list[0])
list[0] = -2

# getting last element
# (negative indexing starting from -1 at the end)
print(list[-1])

# getting first three elements from the list
print(list[0:3])

# getting last free elements from the list
# last element in negative indexing using subrange is inaccessible
print(list[-4:-1])

# the same free elements as previously but with positive indexing
print(list[1:4])
[/cc]

Storing different object types in lists

[cc lang=”python”]
# list of integers
list = [ 1, 2, 3, 4]
print(list)

# list of floats
list = [ 1.0, 2.0, 3.0 ]
print(list)

# list of strings
list = [ “one”, “two” , “three”]
print(list)

# list of mixed types
list = [ “one”, 1, 1.0, “two”, “three” ]
print(list)
print(list[0], list[2], list[-1])
[/cc]

Standard operations with python lists

[cc lang=”python” height=”1090px”]
# typical list of colors
list = [ “red”, “pink”, “blue”]
print(list)

# add new element at the end of the list
list.append(“green”)
print(list)

# add element at the begining of the list
list.insert(0,”yellow”)
print(list)

# add element at any existing position in the list
# we move existing element (here “blue”) one position forward
index = 3
list.insert(index,”purple”)
print(list)

# remove element by value
list.remove(“purple”)
print(list)

# remove element by index with getting the element
index = 2
elem = list.pop(index)
print(elem)
print(list)

# just remove element without returning it
index = 2
del list[index]
print(list)

# delete last element
list.pop()
print(list)

# clean the list
list.clear()
print(list)

# extend existing list (now it is empty) with new ones added at the end
list.extend( [ “pink”, “blue”, “green”] )
print(list)

# reverse the order in the list
list.reverse()
print(list)

# extend list with new colors
# (the same type of variables inside the list as before)
list.extend( [“yellow”, “green”] )
list.sort()
print(list)

# get number of elements in the list
print(list.count(“green”) )

# extend list with mixed type elements and sort them
list.extend( [4, “one”, 5.0, -1.0, -3, “green” ])
# uncomment line below to see the results
# list.sort()
print(list)
[/cc]

Copy and assign two lists in python

[cc lang=”python”]
# create two lists
list1 = [ “one”, “two” , “three”]
list2 = []
print(list1)
print(list2)

# assign one list to another
list2 = list1
list2[1] = “four”
print(list1)
print(list2)

# copy one list to another one
list2 = list1.copy()
list2[1] = “two”
print(list1)
print(list2)
[/cc]