Lists In Python – I

Lists are compound data types, items of lists are enclosed with [], square brackets and are separated by comma. 

A list definition:

mylist = [1, 'two', 'xyz', 8.35, True]

#printing list:

print(mylist)


#output: 

[1, 'two', 'xyz', 8.35, True]


We saw items in the list can be different data types, in our example: integer, string, float, boolean.


In some way, list is similar with arrays from C (C++, C#) hence items can be accessed based on index i.e. 

mylist = [1, 'two', 'xyz', 8.35, True]

print(mylist[0]) #first item from list have index 0

print(mylist[2])


#output:

1

xyz


Supplmentary, lists have slice operator, examples:

mylist = [1, 'two', 'xyz', 8.35, True]

print(mylist[0:3]) #it will print items 0, 1, 2 

print(mylist[2:])  #it will print items from 2 to the end

print(mylist[:3])  #it will print items from the biginning till item with index 3-1


#output: 

[1, 'two', 'xyz']

['xyz', 8.35, True]

[1, 'two', 'xyz']


Lists support -1 like index and it represent last item from list, example:

mylist = [1, 'two', 'xyz', 8.35, True]

print(mylist[-1])


#output:

True


+ Sign can be used to concatenate lists, example:

mylist = [1, 'two', 'xyz', 8.35, True]

thelist = [2, False, 'bb']

print(mylist+thelist)


#output:

[1, 'two', 'xyz', 8.35, True, 2, False, 'bb']


* Asterisk sign in list case is repetition operator, example: 

list2 = [2, True]

print(list2*2)

print(list2[1]*2)


#output:

[2, True, 2, True]