Professional Documents
Culture Documents
• >>>print(list1(range(1,50,3)))
• o/p: [1, 4, 7, 10, 13, 16, 19, 22, 25, 28, 31, 34, 37, 40, 43, 46, 49]
• >>>print(x(range(1,5)))
• NameError: name 'x' is not defined
range(1, 10, 2)
o/p: range(1, 10, 2)
print(range(1, 10, 2))
o/p: range(1, 10, 2)
print(list1(range(1, 10, 2)))
o/p: [1, 3, 5, 7, 9]
•Finally, there is a special list1 that contains no elements. It is called the empty list1, and it is denoted
[].
With all these ways to create list1s, it would be disappointing if we couldn't assign list1 values to
variables or pass list1s as arguments to functions. We can. For example:
vocabulary = ["ameliorate", "castigate", "defenestrate"]
numbers = [17, 123]
empty = []
print (vocabulary, numbers, empty)
['ameliorate', 'castigate', 'defenestrate'] [17, 123] []
Accessing elements
•The syntax for accessing the elements of a list1 is the same as the syntax for accessing the
characters of a string the bracket operator ([ ]). The expression inside the brackets specifies
the index. Remember that the indices start at 0:
print (numbers[0])
numbers[1] = 5
•The bracket operator can appear anywhere in an expression. When it appears on the left side
of an assignment, it changes one of the elements in the list1, so the one-eth element of
numbers (at index 1), which used to be 123, is now 5 (123 is replaced with new assigned
value but index is again 1)
•Any integer expression can be used as an index:
>>> numbers[3-2] #3-2=1, so picked value of index 1
5
>>> numbers[1.0]
TypeError: sequence index must be integer
If you try to read or write an element that does not exist, you get a runtime error:
>>> numbers[2] = 5
IndexError: list1 assignment index out of range.
If an index has a negative value, it counts backward from the end of the list1:
>>> numbers[-1]
5
>>> numbers[-2]
17
>>> numbers[-3]
IndexError: list1 index out of range
numbers[-1] is the last element of the list1, numbers[-2] is the second to last, and
numbers[-3] doesn't exist.
It is common to use a loop variable as a list1 index. For example:
horsemen = ["war", "famine", "pestilence", "death"]
i=0
while i < 4:
print ( horsemen [ i ] )
i=i+1
This while loop counts from 0 to 4. When the loop variable i is 4, the condition fails and the
loop terminates. So the body of the loop is only executed when i is 0, 1, 2, and 3.
Each time through the loop, the variable i is used as an index into the list1, printing the i-eth
element. This pattern of computation is called a list1 traversal.
list1 length
The function len returns the length of a list1. It is a good idea to use this value as the upper
bound of a loop instead of a constant. That way, if the size of the list1 changes, you won't
have to go through the program changing all the loops; they will work correctly for any size
list1. For example:
horsemen = ["war", "famine", "pestilence", "death"]
i=0
list1 operations
The + operator concatenates list1s:
>>> a = [1, 2, 3]
>>> b = [4, 5, 6]
>>> c = a + b
>>> print c
[1, 2, 3, 4, 5, 6]
Operations
on list1
Use of append() on list1
• print(list11) • o/p:
• ['a', 'b', 'c', 1, 2, 3]
o/p: o/p:
['a', 'b', 'c', [1, 2, 3]] ['a', 'b', 'c', 1, 2, 3]
•
Colon ( : ) operator in Python
Use : to do Slicing in python >>> string[-6:-1]
and get substring of a 'world'
string. >>> string[-9:]
'o, world!'
>>> "Hello, world!"[3:9] >>> string[:-8]
'lo, wo' 'Hello'
>>> string[:]
>>> string = "Hello, world!"
'Hello, world!‘
>>> string[:5]
'Hello'
Similarly, the * operator repeats a list1 a given number of times. For example:
>>> [0] * 4
[0, 0, 0, 0]
>>> [1, 2, 3] * 3
[1, 2, 3, 1, 2, 3, 1, 2, 3]
The first example repeats [0] four times. The second example repeats the list1 [1, 2, 3] three times.
•list1 slices
The slice operations also work on list1s. For example:
>>> list1 = ['a', 'b', 'c', 'd', 'e', 'f']
>>> list1[1:3] # 1 means to start at second element in the list1 and 3 means to end at the fourth element in the list1, but
do not include it.
['b', 'c']
>>> list1[:4]
['a', 'b', 'c', 'd']
>>> list1[3:]
['d', 'e', 'f']
If you omit the first index, the slice starts at the beginning. If you omit the second, the slice goes to the end.
So if you omit both, the slice is really a copy of the whole list1. For example:
>>> list1[ :]
['a', 'b', 'c', 'd', 'e', 'f']
>>>print ( list1[ : : -1]) #reverse of above list1
As you might expect, del handles negative indices and causes a runtime error if the index is out of range.
You can use a slice as an index for del. For example:
>>> list1 = ['a', 'b', 'c', 'd', 'e', 'f']
>>> del list1[1:5] # 5 means 5-1 i.e. till index 4. and default index start is 0.
>>> print list1
['a', 'f']
As usual, slices select all the elements up to, but not including, the second index.
Slicing or Slice
• We can specify where to start the slicing, and where to end. Also can
specify the step.
Syntax: slice(start, stop, step)
• Parameters:
• start: Starting index where the slicing of object starts.
• stop: Ending index where the slicing of object stops.
• step: It is an optional argument that determines the increment
between each index for slicing.
• print(n[show]) Let:
slice(7, 50, 2)
n[s]
[7, 9, 11, 13, 15, 17, 19]
• o/p: [1, 3, 5, 7, 9] (no error), print values from range
s
Exercise
In one case, a and b refer to two different things that have the same value.
In the second case, they refer to the same thing. These “things" have names they are
called objects.
An object is something a variable can refer to.
Every object has a unique identifier, which we can obtain with the id function.
By printing the identifier of a and b, we can tell whether they refer to the same object. For
example:
>>> id(a)
135044008
>>> id(b)
135044008
In fact, we get the same identifier twice, which means that Python only created one string,
and both a and b refer to it.
Interestingly, list1s behave differently. When we create two list1s, we get two objects. For
example:
a and b have the same value but do not refer to the same
object.
Aliasing
Since variables refer to objects, if we assign one variable to another, both variables refer to
the same object. For example:
>>> a = [1, 2, 3]
>>> b=a
In this case, the state diagram looks like this:
Because the same list1 has two different names, a and b, we say that it is aliased.
Changes made with one alias affect the other. For example:
>>> b[0] = 5
>>> print a
[5, 2, 3]
Cloning list1s
If we want to modify a list1 and also keep a copy of the original, we need to be able to make
a copy of the list1 itself, not just the reference. This process is sometimes called cloning, to
avoid the ambiguity of the word “copy”.
The easiest way to clone a list1 is to use the slice operator. For example:
>>> a = [1, 2, 3]
>>> b = a[:]
>>> print b
[1, 2, 3]
Taking any slice of a creates a new list1. In this case the slice happens to consist of the whole
list1.
b = a [0:1] # will print only 1 element at index 0. as 1-1=0. so end is again 0 index.
b=a[0:2]
b
[1, 2]
a
[1, 2, 3]
Now we are free to make changes to b without worrying about a. For example:
>>> b[0] = 5
>>> print a
[1, 2, 3]
list1 parameters
Passing a list1 as an argument actually passes a reference to the list1, not a copy of the list1. For
example, the function head takes a list1 as an argument and returns the first element. For example:
def head(list1):
return list1[0] # only 1st element of list1
Here's how it is used:
>>> numbers = [1, 2, 3]
>>> head(numbers)
1
The parameter list1 and the variable numbers are aliases for the same object.
The state diagram looks like this:
Since the list1 object is shared by two frames, we drew it between them.
If a function modifies a list1 parameter, the caller sees the change. For example:
deleteHead removes the first element from a list1:
def deleteHead(list1):
del list1[0]
Here's how deleteHead is used:
>>> numbers = [1, 2, 3]
>>> deleteHead(numbers) #it is not inbuilt function/method
>>> print numbers
[2, 3]
If a function returns a list1, it returns a reference to the list1. For example, tail returns a list1 that
contains all but the first element of the given list1:
def tail(list1):
return list1[1:]
Here's how tail is used:
>>> numbers = [1, 2, 3]
>>> rest = tail(numbers)
>>> print rest
[2, 3]
Because the return value was created with the slice operator, it is a new list1. Creating rest, and any
subsequent changes to rest, have no effect on numbers.
Nested list1s
A nested list1 is a list1 that appears as an element in another list1. In this example of list1, the three-
eth element is a nested list1:
>>> list1 = ["hello", 2.0, 5, [10, 20]]
If we print list1[3], we get [10, 20].
To extract an element from the nested list1, we can proceed in two steps:
>>> elt = list1[3]
>>> elt[0]
10
print(song.split())
o/p: ['The', '#', 'rain', 'in', '#', 'Spain...']
x = song.split("#", 1)
print(x)
#o/p: ['The ', ' rain in # Spain...']
– song = "The # rain in # Spain..."
–song.split("#")
–o/p: ['The ', ' rain in ', ' Spain...']
• An optional argument called a delimiter can be used to specify which characters to use as
word boundaries. The following example uses the string ai as the delimiter. For example:
• print(song.split("#", 2))
• Output is:
•Like split, join takes an optional delimiter that is inserted between elements:
>>> “_”.join(list1)
'The_rain_in_Spain...'
• text = ['Python', 'is', 'a', 'fun', 'programming', 'language']
• print('#'.join(text))
• o/p: Python#is#a#fun#programming#language
• If we do like: print(‘’.join(text))
• o/p: Pythonisafunprogramminglanguage
• # .join() with list1s
• numlist1 = ['1', '2', '3', '4']
• separator = ', '
• print(separator.join(numlist1))
• o/p: 1abc2abc3
• Note: s1 is acting like separator on s2 elements
• 1. list11.append(obj) - append obj at last
– list1=[1,2,3,4,3,3,5,2,2,2,2]
– list1.append(5)
• 2. list1.count(obj)- count no. of occurrence of obj in list1.e.g: list1.count(2)
• 3. list1.index(obj)-return index of 1st occurrence of obj
• 4. list1.remove(obj)- remove 1st occurrence obj from list1
• 5. list1.pop(obj)- it can be used to remove any element from the list1, if we know the index of
the element that we want to delete.
• 6. list1.reverse()- reverse list1
• 7. list1.sort()- to sort elements
• 8. min(list11)- gives min of list1
• 9. max(list11)- gives max of list1
• 10. del list1[index]- deletes the value on the provided index.
• 11. list1.insert(index,item)- inserts the given item onto the given index number.
list1.insert(1, 2.99999999)
Exercise: a=[10,20,30,"abc",10]
• Prform following:
• a.append("Hi")
• a.count(10)
• a.index(10)
• a.remove(20)
• a. reverse()
• * For integer list1 like : a=[10,20,30,40,10,10,20,40]
• PERFORM FOLLOWING:
• len(a)
• min(a)
• max(a)
• sum(a)
• a.sort()
• a.reverse()
• a.count(10)
• a.index(10)
• a.remove(10)
• a.append(10)
• a.insert(2,999) # 2 is index, 999 is value to insert
• list.remove(x) removes the first occurrence of value x from the list,
but it fails to remove all occurrences of value x from the list.
• l=["Hello", "HRU", "Python", "LIKE", "YOU"]
• pick= [ i[0] for i in l]
• print(pick)
• o/p: #['H', 'H', 'P', 'L', 'Y']
• x=["Hello", "HRU", "Python", "LIKE", "YOU"]
• y=["Computer", "Science", "Engineering"]
x=[ [1]*4 ] *5
• pick = [x+y for x in "*" for y in "123456"] print(x)
#[[1, 1, 1, 1], [1, 1, 1, 1], [1, 1, 1, 1], [1, 1, 1, 1], [1, 1, 1, 1]]
• print(pick)
• #['*1', '*2', '*3', '*4', '*5', '*6']
x[1][2]=5
• #list1 creation shortcuts print(x)
• x=["*"]*5
#[[1, 1, 5, 1], [1, 1, 5, 1], [1, 1, 5, 1], [1, 1, 5, 1], [1, 1, 5, 1]]
• print (x)
print(len(x)) #o/p=5
• #['*', '*', '*', '*', '*']
#Combining list1s
• Or
• lis1.extend(lis2)
• print(lis1)
Unpack a list1 using
*
• list11 = ["This" , "is", "a", "Python", "program"]
• list12 = [10, 9,5,3,10]
• x=[*list11 + *list12 ]
– #use comma to merge, * to unpack
• print(x)