Lists in Python 3

Lists are mutable sequences that are often used to store homogeneous items.

The items of a list are enclosed in square brackets. Eg: [1,2,3]

The contents of a list can be printed using the print() function.

mylist=[1,2,3]
print(mylist)
[1,2,3] 

The following example demonstrates that lists are mutable(can be changed).

mylist[0]=99
print(mylist)
[99,2,3]

Lists can be thought of as arrays in some ways, though it is not technically accurate. Mapping between indices and list items work similar to those of arrays. The mapping between indices and list items in action:

print(mylist[0])
99
print(mylist[1])
2
print(mylist[2])
3

The in operator can be used to check if a certain item is present in a list.

99 in mylist
True

List operations:

The + operator concatenates two lists.

list1=[1,2]
list2=[3,4]
print(list1+list2)
[1,2,3,4]

The * operator can be used to repeat a list.

print(list1*3)
[1,2,1,2,1,2]

The slice operator : works as follows: it accepts three parameters: start,end and increment(default is 1, and can be omitted) . The following example demonstrates the behavior:

list3=[1,2,3,4,5]
print(list3[2:5] #inclusive of start and excludes end
[3,4,5]

There are many list methods such as append(),pop(),reverse(). The details can be found here.

I will briefly mention list traversal, which uses for loops. I will cover for loops in detail in an upcoming blog.

list4=[8,9,10]
for num in list4:
    print(num)
8
9
10

If the indices of the elements are required:

for ix, num in enumerate(list4):
    print('Index : {} ,value : {}'.format(ix, num))
Index :  0  Value :  8
Index :  1  Value :  9
Index :  2  Value :  10

The enumerate() function is used to traverse the list and obtain the index of each element.

A few notes about lists:

  • They are mutable, so be careful when making changes in-place without saving the original contents
  • The len() function can be used on lists to find the length
  • Strings can be converted to lists using list(string_variable)

The source code for today’s plog can be viewed here.