Basic concepts
Creating and initializing a list:
A list is always declared using square brackets "[]" with the values inside separated by commas ",".>>>myList = [1, 2, 3]
Creates a list with the values 1, 2 and 3
>>>myList = []
Creates an empty list.
A list can have values of multiple types: integer and real numbers, strings, lists or other data types or structures.
The following example is a valid list declaration with values of different types:
>>>myMultiTypeList = ['Hello', 3.4 , [1,2,3]]
>>>range(3) #Range of 3 numbers from 0
[0, 1, 2]
>>>range(2, 5) #Range of number from 2 to 5, excluded
[2, 3, 4]
>>>range(-2,2) #Range from -2 to 2, excluded
[-2, -1, 0, 1]
>>>range(2,8,2) #Range from 2 to 8, excluded, with a step of 2
[2, 4, 6]
>>>range(8,5) #Returns an empty list
[]
>>>range(8,5,-1) #Reverse range from 8 to 5, excluded
[8, 7, 6]
Accessing data on a list:
The easiest way to access data on a list is by providing the index number of the list element inside square brackets, similar to accessing members of an array in languages like C or Java:>>>myList = [10,22,34,46]
>>>myList[0]
10
>>>myList[2]
34
The first index of a list is 0, and the last index of a list with n elements is n-1.
In python you can access the data in a reverse way using negative indexes, the index -1 will always point to the last value on the list:
>>>myList[-1]
46
>>>myList[-4]
10
In a list with n elements the index -n points always to the first element of a list.
The index i is equivalent to the negative index -n+i.
In the myList example the index 1 is equivalent to the index -4+1 = -3
>>>myList[1]==myList[-3]
True
If you try to access to an index that doesn't exist we will get an exception:
>>>myList[5]
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
IndexError: list index out of range
Another way to access data on a list is using the for cycle:
>>> for value in [1,2,3]:
... print value
...
1
2
3
It can be very useful for manipulation of the whole list.
Slicing a list:
You can access a value by its index and in addition you can also access a sequential subset of values using the slice. The slice is represented by the colon ":" operator with the starting index on the left and the stop index on the rigth. Both values are optional. Omitting the start value will return every value from the beginning of the list to the stop value, omitting the stop value is similar, it will return from the start index to the end of the list, omitting both will return the full list. Note that the stop value will not be included in the subset, similar to the stop value in the range function.>>>myList = ['it', 'is', 'time', 'to', 'slice']
>>>myList[2:4]
['time', 'to']
>>>myList[2:3]
['time']
>>>myList[3:3]
[]
>>>myList[2:]
['time', 'to', 'slice']
>>>myList[:3]
['it', 'is', 'time']
>>>myList[:]
['it', 'is', 'time', 'to', 'slice']
Manipulating a List
Changing data on the list
The most basic data change on a list is to assign a new value to an element of the list.>>>myList = range(4)
>>>myList
[0, 1, 2, 3]
>>>myList[1] = 10
>>>myList
[0, 10, 2, 3]
It is possible to change the data using th slice operator too:
>>>myList[1:3]=[6, 6]
>>>myList
[0, 6, 6, 3]
The size of the sliced list doesn't have to be the same as the new assigned values. The old values will be replaced with the new ones no matter what the size is.
>>>myList=range(6)
>>>myList[2:5]
[2, 3, 4]
>>>myList[2:5]=[0,1]
>>>myList
[0, 1, 0, 1, 5]
>>>myList[2:3]
[0]
>>>myList[2:3]=[9,9,9]
>>>myList
[0, 1, 9, 9, 9, 1, 5]
When using the slice only iterables can be assigned, otherwise an exception will be thrown.
>>>myList[2:3] = 1
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: can only assign an iterable
List methods
A list is an object, and like another objects it has its own methods.- append(x)
- adds x to the end of the list, x is a value
- extend(L)
- appends all values of L in the end of the list. L is a list. Passing a value is an error.
- remove(x)
- removes the first element on the list with the value x. If x doesn't exist an exception is thrown.
- index(x)
- return the index of the first element with the value x. If x doesn't exist an exception is thrown.
- pop(i)
- removes and returns the value on the index i. If i is omitted the last value of the list is returned an removed.
- sort()
- sorts the list in ascending order.
- reverse()
- reverses the order of the elements on the list.
>>> myList=range(6)
>>> myList
[0, 1, 2, 3, 4, 5]
>>> myList.append(6)
>>> myList
[0, 1, 2, 3, 4, 5, 6]
>>> myList.extend([7,8,9])
>>> myList
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
>>> a = myList.pop()
>>> a
9
>>> myList
[0, 1, 2, 3, 4, 5, 6, 7, 8]
>>> myList2 = [88, 33, 99, 88, 44, 11]
>>> myList2.index[88]
0
>>> myList2.index(44)
4
>>> myList2.remove(88)
>>> myList2
[33, 99, 88, 44, 11]
>>>myList2.sort()
>>>myList2
>>> myList2.remove(88)
>>> myList2
[33, 99, 88, 44, 11]
>>> myList2.reverse()
>>> myList2
[99, 88, 44, 33, 11]
Operators
=, assign operator
This operator is user to assign a reference to a list. Note that a variable only points to the list on the memory and never contains it. So the assign operator never creates a copy of a list.
>>>myList = [1,2,3] #assigns the reference to the new list
>>>myList2 = myList #myList and myList2 are referencing the same entity
>>>myList2[0] = 0
>>>myList #yes, it's myList, not myList2
[0,2,3]
One of the easiest ways to get a copy of the list is using the a slice operation without any values:
>>>myList = [1,2,3]
>>>myList2 = myList[:] #a slice instanciates always a new list
>>>myList2[0] = 0
>>>myList
[1,2,3]
>>>myList2
[0,2,3]
+, add operator
This operator adds to lists to a new one.
>>>[1,2,3]+[4,5,6]
[1,2,3,4,5,6]
+=, the "extend" operator
This operator works like the extend method of the list object.
>>>myList = [1,2,3]
>>>myList += [4,5]
>>>myList
[1,2,3,4,5]
*, the "repeat" operator
This operator creates a list that creates a new list repeating a defined number of times the sequence of the operated list:
>>>[1,2,3]*2
[1,2,3,1,2,3]
>>>[1,2]*4
[1,2,1,2,1,2,1,2]
>>>[1]*3
[1,1,1]
>>>[]*5
[]
Tuples
A tuple is a data structure similar to a list. The difference is that a tuple is an immutable structure.
The tuple data is represented the same way as a list with curve brackets instead of square brackets.
Creating a tuple
A tuple can be created assigning the values separated by commas. Parenthesis can be used but aren't necessary.>>> myTuple = 1,2,3,4,5
>>> myTuple
(1, 2, 3, 4, 5)
>>> myTuple2 = (1,2,3,4,5)
>>> myTuple2
(1, 2, 3, 4, 5)
Parenthesis are necessary if you want to declare a structure with tuple elements:
>>> myTupleOfTuples = (1, 2, 3), (4, 5, 6)
((1, 2, 3), (4, 5, 6))
Working with tuples
Remember that when you assign any type of data with a comma in the end you are using a tupple:>>>variable =10
>>>tuple = 10,
>>>variable
10
>>>tuple
(10)
As said before a tuple is immutable data structure, so trying to change an element is an error
>>> myTuple[1]
2
>>> myTuple[1] = 10
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: 'tuple' object does not support item assignment
Tuples can also use slices and the same operators as a list. When using operators parenthesis are required.
>>>(1,2)*3
(1,2,1,2,1,2)
>>>(1,2)+(3,4)
(1,2,3,4)
>>>myTuple=(1,2,3)
>>>myTuple+=(4,5)
>>>myTuple
(1,2,3,4,5)
>>>(1,2,3,4,5,6)[2:4]
(3,4)
Nothing new here, you can ask why the += operator works because a tuple is an immutable structure. The reason it works is that the += doesn't add the data of the operand to the assigned tuple, it instantiates a new tuple with the data of the two operands. Remember that a += b is the same as a = a+b. Also have in mind that is the tuple the immutable object, not the variable who refers it.






Yonggang Meng
Invite as author
Good work
Thomas Barron
Invite as author
good work.