You are on page 1of 65

Python Sequences

(list1, Tuple, Set, Dictionary)


Something about String and operations on string
Python Sequences
• list1s : with square brackets [ ]. Mutable-changeable
• Tuples : with simple brackets ( ). immutable
• Sets : with curly brackets { }. targets unique value and delete
duplicate entries, unordered, elements are immutable
• Dictionaries: with curly brackets { } and : operator for key-value pair.
unordered, mutable

• Operations: insert, delete, append, extend, clear, del, , sort, reverse,


remove, pop, discard, add
>>> "Hello, world!"[0]
Something about String
'H' Indexes are numbered from 0 to n-1
>>> "Hello, world!"[1]
'e'
>>> "Hello, world!"[2]
'l' Hel l o ,_wor l d !
>>> "Hello, world!"[3] 0 1 2 3 4 5 6 7 8 9 10 11 12
'l'
>>> "Hello, world!"[4]
'o‘
>>> "Hello, world!"[-2]
'd'
>>> "Hello, world!"[-9]
'o'
list1s
•A list1 is an ordered set of values, where each value is identified by an index.
The values that make up a list1 are called its elements.
list1s are similar to strings, which are ordered sets of characters, except that the elements of a
list1 can have any type. list1s and strings and other things that behave like ordered sets are
called sequences.
•list1 values
•There are several ways to create a new list1; the simplest is to enclose the elements in square brackets ([ and ]):

[10, 20, 30, 40]


["spam", "bungee", "swallow"]
The first example is a list1 of four integers.
The second is a list1 of three strings.
•The following list1 contains a string, a float, an integer, and another list1:

["hello", 2.0, 5, [10, 20]]


A list1 within another list1 is said to be nested.
list1s that contain consecutive integers are common, so Python provides a simple way to
create them:
>>> print(list1(range(1,5)))
o/p: [1, 2, 3, 4]
>>> print ( list1 [1,5] )
>>> list1 [1,5]
•The range function takes two arguments and returns a list1 that contains all the integers
from the first to the second, including the first but not including the second!
There are two other forms of range. With a single argument, it creates a list1 that starts at 0:
>>> list1(range(10))
• >>> print(list1(range(1,5)))
• o/p: [1, 2, 3, 4]

• >>>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

while i < len(horsemen):


print horsemen[i]
i=i+1
The last time the body of the loop is executed, i is len(horsemen) - 1, which is the index of
the last element. When i is equal to len(horsemen), the condition fails and the body is not
executed, which is a good thing, because len(horsemen) is not a legal index.
Although a list1 can contain another list1, the nested list1 still counts as a single element.
The length of this list1 is four:
['spam!', 1, ['Brie', 'Roquefort', 'Pol le Veq'], [1, 2, 3] ]
list1 membership
in is a boolean operator that tests membership in a sequence (will use in next chapter). For example:
>>> horsemen = ['war', 'famine', 'pestilence', 'death']
>>> 'pestilence' in horsemen
True
>>> 'debauchery' in horsemen
False
Since “pestilence” is a member of the horsemen list1, the in operator returns true. Since
“debauchery” is not in the list1, in returns false.
We can use the not in combination with in to test whether an element is not a member of a list1:
>>> 'debauchery' not in horsemen
True
list1s and for loops
The generalized syntax of a for loop is:
for VARIABLE in list1:
BODY
This statement is equivalent to:
i=0
while i < len(list1):
VARIABLE = list1[i]
BODY
i=i+1
The for loop is more concise because we can eliminate the loop variable, i. Here is the previous loop
written with a for loop. For example:
for horseman in horsemen:
print horseman
It almost reads like English: \For (every) horseman in (the list1 of) horsemen, print (the name of the)
horseman."
Any list1 expression can be used in a for loop. For example:
for number in range(20):
if number % 2 == 0:
print number

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

• list11 = ["a", "b" , • list11 = ["a", "b" , • list11 = ["a", "b" ,


"c"] "c"] "c"]

• list12 = [1, 2, 3] • list12 = [1, 2, 3] • list12 = [1, 2, 3]

• list11.append(list12) • for x in list12: • list11.extend(list12)

• print(list11) • list11.append(x) • print(list11)

• 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

•list1s are mutable


Unlike strings, list1s are mutable, which means we can change their elements.
Using the bracket operator on the left side of an assignment, we can update one of the elements. For
example:
>>> fruit = ["banana", "apple", "quince"]
>>> fruit[0] = "pear"
>>> fruit[-1] = "orange"
>>> print fruit
['pear', 'apple', 'orange']
•With the slice operator we can update several elements at once. For example:
>>> list1 = ['a', 'b', 'c', 'd', 'e', 'f']
>>> list1[1:3] = ['x', 'y']
>>> print list1
['a', 'x', 'y', 'd', 'e', 'f']
list1[1:3] = ['x', '*', '**']
print (list1)
['a', 'x', '*', '**', 'd', 'e', 'f']
•We can also remove elements from a list1 by assigning the empty list1 to them. For
example:
>>> list1 = ['a', 'b', 'c', 'd', 'e', 'f']
>>> list1[1:3] = []
>>> print list1
And we can add elements to a list1 by squeezing them into an empty slice at the desired
location. For example:
>>> list1 = ['a', 'd', 'f']
>>> list1[1:1] = ['b', 'c']
>>> print list1
['a', 'b', 'c', 'd', 'f']
>>> list1[4:4] = ['e']
>>> print list1
['a', 'b', 'c', 'd', 'e', 'f']
list1 deletion
Using slices to delete list1 elements can be awkward, and therefore error-prone.
Python provides an alternative that is more readable. del removes an element from a list1. For example:
>>> a = ['one', 'two', 'three']
>>> del a[1]
>>>print ( a )
['one', 'three']

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.

Return Type: Returns a sliced object containing elements in the given


range only.
n=list1(range(0,20))
• n = [1,2,3,4,5,6,7,8,9,10] s=slice(7,15,2)
n[s]
• show = slice(0, 10, 2) o/p: =[7, 9, 11, 13]

• 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

• 1. Write a Python program to sum all the items in a list1.


• 2. Write a Python program to multiples all the items in a list1.
• 3. Write a Python program to get the largest number from a list1.
• 4. Write a Python program to get the smallest number from a list1.
• 5. Creation of list1 and changing value of any one element, also
display the length of list1.
• WAP to perform ‘+’,’*’, ‘in’, ‘not in’, ‘slicing’ and delete
operations on list1s.
• x=[20,30,10]
• print(sum(x, 200))
• print(sum(x))
Objects and values
If we execute these assignment statements,
a = "banana"
b = "banana"
we know that a and b will refer to a string with the letters "banana". But we can't tell
whether they point to the same string.
There are two possible states:

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

Or we can combine them:


>>> list1[3][1]
20
Bracket operators evaluate from left to right, so this expression gets the three-eth element of list1 and
extracts the one-eth element from it.
Matrices
Nested list1s are often used to represent matrices. For example, the matrix:

might be represented as:


>>> matrix = [[1, 2, 3], [4, 5, 6], [7, 8, 9]]
matrix is a list1 with three elements, where each element is a row of the matrix.
We can select an entire row from the matrix in the usual way:
>>> matrix[1]
[4, 5, 6]
Or we can extract a single element from the matrix using the double-index form:
>>> matrix[1][1]
5
Strings and list1s
Two of the most useful functions in the string module involve list1s of strings.
The split function breaks a string into a list1 of words. By default, any number of whitespace
characters is considered a word boundary. For example:
song = "The # rain in # Spain..."

print(song.split())
o/p: ['The', '#', 'rain', 'in', '#', 'Spain...']

Max parameter with split


# setting the maxsplit parameter to 1, will return a list1 with 2 elements!

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:

• Notice that the delimiter doesn't appear in the list1.


• song = "#The # rain ##in # Spain...“

• print(song.split("#", 2))
• Output is:

–['', 'The ', ' rain ##in # Spain...']


•The join function is the inverse of split. It takes a list1 of strings and concatenates
the elements with a space between each pair. For example:
>>> list1 = ['The', 'rain', 'in', 'Spain...']
s=""
s=s.join(list1)
print(s)
o/p: TheraininSpain...

•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))

• # .join() with tuples


• numTuple = ('1', '2', '3', '4')
• print(separator.join(numTuple))
• s1 = 'abc'
• s2 = '123'
• # each element of s2 is separated by s1
• # '1'+ 'abc'+ '2'+ 'abc'+ '3'
• print (s1.join(s2) )

• 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

print([1,2] + [3,4]) #o/p=[1, 2, 3, 4]


pop() parameters
• The pop() method takes a single argument (index).
• The argument passed to the method is optional. If not passed, the
default index -1 is passed as an argument (index of the last item).
• If the index passed to the method is not in range, it throws
IndexError: pop index out of range exception.
Questions
Q1. Creation of list1 and changing value of any one element, also display the length of list1.
Q2. Create a list1 and append two elements in it.
Q3. Create a list1 and sort it.
Q4. Duplicate of sum
Q5. Program to compare elements of list1.
Q6. Duplicate of Multiply
Q7. Count the occurrence of element in list1.
Q8. Reverse a list1.
Q9.Write a loop that traverses the previous list1 and prints the length of each element. What
happens if you send an integer to len?
Q10. Describe the relationship between string.join(string.split(song)) and song. Are they
the same for all strings? When would they be different? (song is a string)
• Compare two list1
• Merge two list1
Compare two list1s
Merge Two list1s

• Can use + operator


• Can use extend()
• Can use loop concept
• Using unpack * concept
Merge 2 list1s

• lis1 = ["This" , "is", "a", “Python", "program"]


• lis2 = [10, 9,5,3,10]
• print(lis1 + lis2 )

• 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)

You might also like