SlideShare a Scribd company logo
MODULE 3 – PART 1
LISTS
By,
Ravi Kumar B N
Assistant professor, Dept. of CSE
BMSIT & M
✓ List: It is a sequence of values and values can be of any type.
The values in list are called elements or sometimes items.
There are several ways to create a new list; the simplest is to enclose the
elements in square brackets ([ and ]):
Example:
[10, 20, 30, 40] List of integers
['crunchy frog', 'ram bladder', 'lark vomit’] List of strings
✓ The elements of a list don’t have to be the same type.
✓ Nested List: A list within another list is nested.
The following list contains a string, a float, an integer, and another list:
['spam', 2.0, 5, [10, 20]]
✓ Empty List: A list that contains no elements is called an empty list;
you can create one with empty brackets, [].
BASICS
✓ Assigning list values to variables:
>>> cheeses = ['Cheddar', 'Edam', 'Gouda’]
>>> numbers = [17, 123]
>>> empty = []
>>> print cheeses, numbers, empty
Output: ['Cheddar', 'Edam', 'Gouda'] [17, 123] []
✓ The syntax for accessing the elements of a list is the same as for
accessing the characters of a string—the bracket operator.
The expression inside the brackets specifies the index. Indices always starts at 0
>>> print cheeses[0]
Output: Cheddar
✓ List indices work the same way as string indices:
▪ Any integer expression can be used as an index.
▪ If you try to read or write an element that does not exist, you get an Index Error.
▪ If an index has a negative value, it counts backward from the end of the list.
>>>my_list = ['p','r','o','b',’e’]
>>>print(my_list[0])
Output: p
>>>print(my_list[2])
Output: o
>>>print(my_list[4])
Output: e
>>>my_list[4.0]
Output: Error! Only integer can be used for indexing
# Nested List
>>>n_list = ["Happy", [2,0,1,9]]
# Nested indexing
>>>print(n_list[0][1])
Output: a
>>>print(n_list[1][3])
Output: 5
Samples
>>>a = "bee"
>>>print(list(a))
Output: ['b', 'e', 'e']
>>>a = ("I", "am", "a", "tuple")
>>>print(list(a))
['I', 'am', 'a', 'tuple']
LISTS ARE MUTABLE
✓ Unlike strings, lists are mutable because we can change the order of items in a list or
reassign an item in a list.
When the bracket operator appears on the left side of an assignment, it identifies the
element of the list that will be assigned.
>>> numbers = [17, 123]
>>> print(numbers)
Output: [17, 123]
>>> numbers[1] = 5
>>> print(numbers)
Output: [17, 5]
The one-eth element of numbers, which used to be 123, is now 5.
We can use in operator on lists:
>>> cheeses = ['Cheddar', 'Edam', 'Gouda’]
>>> 'Edam' in cheeses
Output: True
>>> 'Brie' in cheeses
Output: False
Traversing a list:
The most common way to traverse the elements of a list is with
a for loop. The syntax is the same as for strings:
This works well if we only need to read the elements of the list
Listra.py
# iterate over a list
list = [1, 3, 5, 7, 9]
# Using for loop
for i in list:
print(i)
Output:
1
3
5
7
9
✓ If you want to write or update the elements, you need the indices.
A common way to do that is to combine the functions range and len:
Listrav1.py
# code to iterate over a list
list = [1, 3, 5, 7, 9]
# getting length of list
length = len(list)
# Iterating the index
# same as 'for i in range(len(list))’
for i in range(length):
list[i] = list[i]+5
print(list)
Output:
[6, 8, 10, 12, 14]
This loop traverses the list and updates each
element. len returns the number of elements
in the list. range returns a list of indices from
0 to n−1, where n is the length of the list.
Listlen.py
# code to find the length of nested list
list1=['spam', 1, ['Brie', 'Roquefort', 'Pol le Veq'], [1, 2, 3]]
print(len(list1))
Output:
4
Although a list can contain another list, the nested list still counts as a
single element. The length of this list is four:
A for loop over an empty list never executes the body:
Emptylistra.py
empty=[]
for x in empty:
print('It never executes’)
Output:
No output
List Concatenation: The + operator concatenates lists
>>> a = [1, 2, 3]
>>> b = [4, 5, 6]
>>> c = a + b
>>> print c
[1, 2, 3, 4, 5, 6]
List Repetition: Similarly, the * operator repeats a list a given number of times
>>> [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 list [1, 2, 3] three times.
LIST OPERATIONS
LIST SLICES
The slice operator also works on lists:
>>> t = ['a', 'b', 'c', 'd', 'e', 'f’]
>>> t[1:3]
['b', ‘c’]
If you omit the first index, the slice starts at the beginning.
>>> t[:4]
['a', 'b', 'c', ‘d’]
If you omit the second, the slice goes to the end.
>>> t[3:]
['d', 'e', 'f’]
So if you omit both, the slice is a copy of the whole list Lists
>>> t[:]
['a', 'b', 'c', 'd', 'e', 'f’]
A slice operator on the left side of an assignment can update multiple elements:
>>> t = ['a', 'b', 'c', 'd', 'e', 'f’]
>>> t[1:3] = ['x', 'y’]
>>> print t
['a', 'x', 'y', 'd', 'e', 'f']
LIST METHODS
append: It adds a new element to the end of a list:
>>> t = ['a', 'b', 'c’]
>>> t.append('d’)
>>> print t
['a', 'b', 'c', 'd’]
extend: It takes a list as an argument and appends all of the elements:
>>> t1 = ['a', 'b', 'c’]
>>> t2 = ['d', 'e’]
>>> t1.extend(t2)
>>> print t1
['a', 'b', 'c', 'd', 'e’]
This example leaves t2 unmodified.
Sort: It arranges the elements of the list from low to high:
>>> t = ['d', 'c', 'e', 'b', 'a’]
>>> t.sort()
>>> print t
['a', 'b', 'c', 'd', 'e’]
Most list methods are void; they modify the list and return None.
>>>t.append('d','e’)
Traceback (most recent call last):
File "<pyshell#32>", line 1, in <module>
t.append('d','e’)
TypeError: append() takes exactly one argument (2 given)
DELETING ELEMENTS
pop()- This method will be used If we know the index of the element to be deleted.
It modifies the list and returns the element that was removed.
If we don’t provide an index, it deletes and returns the last element.
>>> t = ['a', 'b', 'c’]
>>> x = t.pop(1)
>>> print t
['a', 'c’]
>>> print x
b
del- If we don’t need the removed value, you can use the del operator:
>>> t = ['a', 'b', 'c’]
>>> del t[1]
>>> print t
['a', 'c’]
To remove more than one element, you can use del with a slice index:
>>> t = ['a', 'b', 'c', 'd', 'e', 'f’]
>>> del t[1:5]
>>> print t
['a', 'f']
remove()- If we know the element we want to remove (but not the index), you can use remove:
>>> t = ['a', 'b', 'c’]
>>> t.remove('b’)
>>> print t
['a', 'c’]
It takes exactly one argument.
The return value from remove is None.
insert()- It inserts an item at a specified position.
>>> t = ['a', ‘c', ‘d’]
>>> t.insert(1,’b’)
[‘a’,’b’,’c’,’d’]
It is important to distinguish between operations that modify lists and operations
that create new lists.
For example, the append method modifies a list, but
>>> t1 = [1, 2]
>>> t2 = t1.append(3)
>>> print t1
[1, 2, 3]
>>> print t2
None
the + operator creates a new list:
>>> t3 = t1 + [3]
>>> print t3
[1, 2, 3]
>>> t1 is t3
False
LISTS AND FUNCTIONS
built-in functions that can be used on lists:
>>> nums = [3, 41, 12, 9, 74, 15]
>>> print len(nums)
6
>>> print max(nums)
74
>>> print min(nums)
3
>>> print sum(nums)
154
>>> print sum(nums)/len(nums)
25
The sum() function only works when the list elements are numbers.
The other functions (max(), len(), etc.) work with lists of strings and other types that can be comparable.
EXAMPLES
# code to find the average numbers using list functions
numlist = list()
while ( True ) :
inp = input('Enter a number: ')
if inp == 'done' : break
value = float(inp)
numlist.append(value)
average = sum(numlist) / len(numlist)
print('Average:',average)
Output:
Enter a number: 1
Enter a number: 2
Enter a number: 3
Enter a number: 4
Enter a number: done
Average: 2.5
# Display the integers entered by the user in ascending order.
data=[]
# read values, adding them to the list, until the user enters 0
num = int(input("enter a number - 0 to quit:"))
while num != 0:
data.append(num)
num = int(input("enter a number - 0 to quit:"))
#sort numbers
data.sort()
#Display the values
print("sorted numbers are")
for num in data:
print(num,end=" ")
Output:
enter number of elements to be sorted:5
enter a number50
enter a number40
enter a number20
enter a number10
enter a number30
sorted numbers are
10 20 30 40 50
LISTS AND STRINGS
list(): A string is a sequence of characters and a list is a sequence of values, but a list of characters is
not the same as a string.To convert from a string to a list of characters, we can use list() method:
>>> s = 'spam’
>>> t = list(s)
>>> print t
['s', 'p', 'a', 'm’]
The list function breaks a string into individual letters.
split():If we want to break a string into words, we can use the split method:
>>>txt = "welcome to the jungle"
>>>x = txt.split()
>>>print(x)
['welcome', 'to', 'the', 'jungle’]
you can use the index operator (square bracket) to look at a particular word in the list
>>>print(x[3])
jungle
split(delimiter): You can call split with an optional argument called a delimiter that specifies which
characters to use as word boundaries.
The following example uses a hyphen as a delimiter:
>>> s = ‘10-05-2020’
>>> s.split(‘-’)
[‘10', ‘05', ‘2020’]
join(): is the inverse of split. It takes a list of strings and concatenates the elements.
join is a string method, so you have to invoke it on the delimiter and pass the list as a parameter:
>>> t = ['pining', 'for', 'the', 'fjords’]
>>> delimiter = ' ‘
>>> delimiter.join(t)
'pining for the fjords'
#to print out the day of the week from those lines that start with “From ”
fhand = open('mbox.txt')
for line in fhand:
line = line.rstrip()
if not line.startswith('From:') : continue
words = line.split()
print(words[2])
Output:
Sat
Mon
Fri
mbox.txt
From: stephen.marquard@uct.ac.za Sat Jan 5 09:14:16 2008
Return-Path: <postmaster@collab.sakaiproject.org>
From: louis@media.berkeley.edu Mon Jan 4 16:10:39 2008
Subject: [sakai] svn commit:
From: zqian@umich.edu Fri Jan 4 16:10:39 2008
Return-Path: <postmaster@collab.sakaiproject.org>
If we execute these assignment statements:
a = ‘book’
b = ‘book’
In this example, Python only created one string object, and both a and b refer
to it.
To check whether two variables refer to the same object, you can use the “Is”
operator.
>>> a = ‘book’
>>> b = ‘book’
>>> a is b
True
But when you create two lists, you get two objects:
>>> a = [1, 2, 3]
>>> b = [1, 2, 3]
>>> a is b
False
a
book
b
a [1, 2, 3]
b [1, 2, 3]
OBJECTS AND VALUES
ALIASING
An object with more than one reference has more than one name, so we say that the object is
aliased.
If a refers to an object and we assign b = a, then both variables refer to the same object:
>>> a = [1, 2, 3]
>>> b = a
>>> b is a
True
The association of a variable with an object is called a reference. In this example, there are two
references to the same object
If the aliased object is mutable, changes made with one alias affect the other:
>>> b[0] = 17
>>> print a
[17, 2, 3]
It is important to distinguish between operations that modify lists and operations
that create new lists.
For example, the append method modifies a list, but
>>> t1 = [1, 2]
>>> t2 = t1.append(3)
>>> print t1
[1, 2, 3]
>>> print t2
None
the + operator creates a new list:
>>> t3 = t1 + [3]
>>> print t3
[1, 2, 3]
>>> t2 is t3
False
"""
Exercise 8.1: Write a function called chop that takes a list and modifies it,
removing the first and last elements, and returns None.
Then write a function called middle that takes a list and returns a new list
that contains all but the first and last elements."""
def chop(lst):
del lst[0] # Removes the first element
del lst[-1] # Removes the last element
def middle(lst):
new = lst[1:] # Stores all but the first element
del new[-1] # Deletes the last element
return new
my_list = [1, 2, 3, 4]
my_list2 = [1, 2, 3, 4]
chop_list = chop(my_list)
print(my_list) # Should be [2,3]
print(chop_list) # Should be None
middle_list = middle(my_list2)
print(my_list2) # Should be unchanged
print(middle_list) # Should be [2,3]
Output:
[2, 3]
None
[1, 2, 3, 4]
[2, 3]
THANK
YOU

More Related Content

PDF
Python Regular Expressions
PDF
Python programming : List and tuples
PDF
Python tuples and Dictionary
PDF
List , tuples, dictionaries and regular expressions in python
PDF
Python lists &amp; sets
PDF
Python Variable Types, List, Tuple, Dictionary
Python Regular Expressions
Python programming : List and tuples
Python tuples and Dictionary
List , tuples, dictionaries and regular expressions in python
Python lists &amp; sets
Python Variable Types, List, Tuple, Dictionary

What's hot (20)

PDF
Python programming : Strings
PPTX
Python programming -Tuple and Set Data type
PDF
Python Workshop Part 2. LUG Maniapl
PPTX
List in Python
PPTX
Python Lecture 8
PPTX
Python Lecture 11
PDF
Python list
PDF
PDF
1. python
PDF
Python :variable types
PPTX
Python Lecture 10
PPTX
Basic data structures in python
PDF
List,tuple,dictionary
PPTX
Unit 4 python -list methods
PPTX
Sequence Types in Python Programming
PDF
15CS664-Python Application Programming - Module 3 and 4
PDF
15CS664- Python Application Programming - Module 3
PDF
Python programming : Standard Input and Output
PDF
Arrays in python
Python programming : Strings
Python programming -Tuple and Set Data type
Python Workshop Part 2. LUG Maniapl
List in Python
Python Lecture 8
Python Lecture 11
Python list
1. python
Python :variable types
Python Lecture 10
Basic data structures in python
List,tuple,dictionary
Unit 4 python -list methods
Sequence Types in Python Programming
15CS664-Python Application Programming - Module 3 and 4
15CS664- Python Application Programming - Module 3
Python programming : Standard Input and Output
Arrays in python
Ad

Similar to Pytho lists (20)

PPTX
Lists.pptx
PDF
GE3151 PSPP UNIT IV QUESTION BANK.docx.pdf
PPTX
Pythonlearn-08-Lists (1).pptxaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa...
PPTX
Python list tuple dictionary presentation
PPTX
Pythonlearn-08-Lists.pptx
PPTX
List_tuple_dictionary.pptx
PPTX
List_tuple_dictionary.pptxList_tuple_dictionary.pptx
PDF
python_avw - Unit-03.pdf
PPTX
Python lists
PPTX
PYTHON-PROGRAMMING-UNIT-III.pptx kghbg kfhjf jruufg jtuuf
PPTX
Pythonlearn-08-Lists.pptx
PPT
UNIT 4 PY.ppt - DATA STRUCTURE IN PYTHON
PDF
Py4Inf-08-Lists ListsListsListsListsListsListsListsListsListsListsListsLists.pdf
PDF
Python elements list you can study .pdf
PDF
The Ring programming language version 1.9 book - Part 29 of 210
PDF
The Ring programming language version 1.8 book - Part 27 of 202
PPTX
Unit 4.pptx python list tuples dictionary
DOCX
Python Materials- Lists, Dictionary, Tuple
PPTX
Lecture2.pptx
Lists.pptx
GE3151 PSPP UNIT IV QUESTION BANK.docx.pdf
Pythonlearn-08-Lists (1).pptxaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa...
Python list tuple dictionary presentation
Pythonlearn-08-Lists.pptx
List_tuple_dictionary.pptx
List_tuple_dictionary.pptxList_tuple_dictionary.pptx
python_avw - Unit-03.pdf
Python lists
PYTHON-PROGRAMMING-UNIT-III.pptx kghbg kfhjf jruufg jtuuf
Pythonlearn-08-Lists.pptx
UNIT 4 PY.ppt - DATA STRUCTURE IN PYTHON
Py4Inf-08-Lists ListsListsListsListsListsListsListsListsListsListsListsLists.pdf
Python elements list you can study .pdf
The Ring programming language version 1.9 book - Part 29 of 210
The Ring programming language version 1.8 book - Part 27 of 202
Unit 4.pptx python list tuples dictionary
Python Materials- Lists, Dictionary, Tuple
Lecture2.pptx
Ad

More from BMS Institute of Technology and Management (12)

PDF
Artificial Neural Networks: Introduction, Neural Network representation, Appr...
PPTX
Decision Tree Learning: Decision tree representation, Appropriate problems fo...
PPTX
Classification: MNIST, training a Binary classifier, performance measure, mul...
PPTX
ML_Module1.Introduction_and_conceprtLearning_pptx.pptx
PDF
Software Engineering and Introduction, Activities and ProcessModels
PDF
PPTX
Introduction to the Python
DOCX
15CS562 AI VTU Question paper
PPTX
PPT
Problems, Problem spaces and Search
PDF
Introduction to Artificial Intelligence and few examples
Artificial Neural Networks: Introduction, Neural Network representation, Appr...
Decision Tree Learning: Decision tree representation, Appropriate problems fo...
Classification: MNIST, training a Binary classifier, performance measure, mul...
ML_Module1.Introduction_and_conceprtLearning_pptx.pptx
Software Engineering and Introduction, Activities and ProcessModels
Introduction to the Python
15CS562 AI VTU Question paper
Problems, Problem spaces and Search
Introduction to Artificial Intelligence and few examples

Recently uploaded (20)

PPTX
Welding lecture in detail for understanding
PPTX
M Tech Sem 1 Civil Engineering Environmental Sciences.pptx
PDF
Mitigating Risks through Effective Management for Enhancing Organizational Pe...
PPT
Mechanical Engineering MATERIALS Selection
PPTX
Engineering Ethics, Safety and Environment [Autosaved] (1).pptx
PPTX
MET 305 2019 SCHEME MODULE 2 COMPLETE.pptx
PDF
composite construction of structures.pdf
PDF
Well-logging-methods_new................
PPTX
IOT PPTs Week 10 Lecture Material.pptx of NPTEL Smart Cities contd
PDF
keyrequirementskkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkk
PDF
R24 SURVEYING LAB MANUAL for civil enggi
PPTX
CH1 Production IntroductoryConcepts.pptx
PDF
July 2025 - Top 10 Read Articles in International Journal of Software Enginee...
PDF
Embodied AI: Ushering in the Next Era of Intelligent Systems
PPTX
OOP with Java - Java Introduction (Basics)
PDF
SM_6th-Sem__Cse_Internet-of-Things.pdf IOT
PPTX
KTU 2019 -S7-MCN 401 MODULE 2-VINAY.pptx
PDF
Mohammad Mahdi Farshadian CV - Prospective PhD Student 2026
PDF
TFEC-4-2020-Design-Guide-for-Timber-Roof-Trusses.pdf
PPTX
UNIT 4 Total Quality Management .pptx
Welding lecture in detail for understanding
M Tech Sem 1 Civil Engineering Environmental Sciences.pptx
Mitigating Risks through Effective Management for Enhancing Organizational Pe...
Mechanical Engineering MATERIALS Selection
Engineering Ethics, Safety and Environment [Autosaved] (1).pptx
MET 305 2019 SCHEME MODULE 2 COMPLETE.pptx
composite construction of structures.pdf
Well-logging-methods_new................
IOT PPTs Week 10 Lecture Material.pptx of NPTEL Smart Cities contd
keyrequirementskkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkk
R24 SURVEYING LAB MANUAL for civil enggi
CH1 Production IntroductoryConcepts.pptx
July 2025 - Top 10 Read Articles in International Journal of Software Enginee...
Embodied AI: Ushering in the Next Era of Intelligent Systems
OOP with Java - Java Introduction (Basics)
SM_6th-Sem__Cse_Internet-of-Things.pdf IOT
KTU 2019 -S7-MCN 401 MODULE 2-VINAY.pptx
Mohammad Mahdi Farshadian CV - Prospective PhD Student 2026
TFEC-4-2020-Design-Guide-for-Timber-Roof-Trusses.pdf
UNIT 4 Total Quality Management .pptx

Pytho lists

  • 1. MODULE 3 – PART 1 LISTS By, Ravi Kumar B N Assistant professor, Dept. of CSE BMSIT & M
  • 2. ✓ List: It is a sequence of values and values can be of any type. The values in list are called elements or sometimes items. There are several ways to create a new list; the simplest is to enclose the elements in square brackets ([ and ]): Example: [10, 20, 30, 40] List of integers ['crunchy frog', 'ram bladder', 'lark vomit’] List of strings ✓ The elements of a list don’t have to be the same type. ✓ Nested List: A list within another list is nested. The following list contains a string, a float, an integer, and another list: ['spam', 2.0, 5, [10, 20]] ✓ Empty List: A list that contains no elements is called an empty list; you can create one with empty brackets, []. BASICS
  • 3. ✓ Assigning list values to variables: >>> cheeses = ['Cheddar', 'Edam', 'Gouda’] >>> numbers = [17, 123] >>> empty = [] >>> print cheeses, numbers, empty Output: ['Cheddar', 'Edam', 'Gouda'] [17, 123] [] ✓ The syntax for accessing the elements of a list is the same as for accessing the characters of a string—the bracket operator. The expression inside the brackets specifies the index. Indices always starts at 0 >>> print cheeses[0] Output: Cheddar ✓ List indices work the same way as string indices: ▪ Any integer expression can be used as an index. ▪ If you try to read or write an element that does not exist, you get an Index Error. ▪ If an index has a negative value, it counts backward from the end of the list.
  • 4. >>>my_list = ['p','r','o','b',’e’] >>>print(my_list[0]) Output: p >>>print(my_list[2]) Output: o >>>print(my_list[4]) Output: e >>>my_list[4.0] Output: Error! Only integer can be used for indexing # Nested List >>>n_list = ["Happy", [2,0,1,9]] # Nested indexing >>>print(n_list[0][1]) Output: a >>>print(n_list[1][3]) Output: 5 Samples >>>a = "bee" >>>print(list(a)) Output: ['b', 'e', 'e'] >>>a = ("I", "am", "a", "tuple") >>>print(list(a)) ['I', 'am', 'a', 'tuple']
  • 5. LISTS ARE MUTABLE ✓ Unlike strings, lists are mutable because we can change the order of items in a list or reassign an item in a list. When the bracket operator appears on the left side of an assignment, it identifies the element of the list that will be assigned. >>> numbers = [17, 123] >>> print(numbers) Output: [17, 123] >>> numbers[1] = 5 >>> print(numbers) Output: [17, 5] The one-eth element of numbers, which used to be 123, is now 5.
  • 6. We can use in operator on lists: >>> cheeses = ['Cheddar', 'Edam', 'Gouda’] >>> 'Edam' in cheeses Output: True >>> 'Brie' in cheeses Output: False Traversing a list: The most common way to traverse the elements of a list is with a for loop. The syntax is the same as for strings: This works well if we only need to read the elements of the list Listra.py # iterate over a list list = [1, 3, 5, 7, 9] # Using for loop for i in list: print(i) Output: 1 3 5 7 9
  • 7. ✓ If you want to write or update the elements, you need the indices. A common way to do that is to combine the functions range and len: Listrav1.py # code to iterate over a list list = [1, 3, 5, 7, 9] # getting length of list length = len(list) # Iterating the index # same as 'for i in range(len(list))’ for i in range(length): list[i] = list[i]+5 print(list) Output: [6, 8, 10, 12, 14] This loop traverses the list and updates each element. len returns the number of elements in the list. range returns a list of indices from 0 to n−1, where n is the length of the list. Listlen.py # code to find the length of nested list list1=['spam', 1, ['Brie', 'Roquefort', 'Pol le Veq'], [1, 2, 3]] print(len(list1)) Output: 4 Although a list can contain another list, the nested list still counts as a single element. The length of this list is four: A for loop over an empty list never executes the body: Emptylistra.py empty=[] for x in empty: print('It never executes’) Output: No output
  • 8. List Concatenation: The + operator concatenates lists >>> a = [1, 2, 3] >>> b = [4, 5, 6] >>> c = a + b >>> print c [1, 2, 3, 4, 5, 6] List Repetition: Similarly, the * operator repeats a list a given number of times >>> [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 list [1, 2, 3] three times. LIST OPERATIONS
  • 9. LIST SLICES The slice operator also works on lists: >>> t = ['a', 'b', 'c', 'd', 'e', 'f’] >>> t[1:3] ['b', ‘c’] If you omit the first index, the slice starts at the beginning. >>> t[:4] ['a', 'b', 'c', ‘d’] If you omit the second, the slice goes to the end. >>> t[3:] ['d', 'e', 'f’] So if you omit both, the slice is a copy of the whole list Lists >>> t[:] ['a', 'b', 'c', 'd', 'e', 'f’] A slice operator on the left side of an assignment can update multiple elements: >>> t = ['a', 'b', 'c', 'd', 'e', 'f’] >>> t[1:3] = ['x', 'y’] >>> print t ['a', 'x', 'y', 'd', 'e', 'f']
  • 10. LIST METHODS append: It adds a new element to the end of a list: >>> t = ['a', 'b', 'c’] >>> t.append('d’) >>> print t ['a', 'b', 'c', 'd’] extend: It takes a list as an argument and appends all of the elements: >>> t1 = ['a', 'b', 'c’] >>> t2 = ['d', 'e’] >>> t1.extend(t2) >>> print t1 ['a', 'b', 'c', 'd', 'e’] This example leaves t2 unmodified. Sort: It arranges the elements of the list from low to high: >>> t = ['d', 'c', 'e', 'b', 'a’] >>> t.sort() >>> print t ['a', 'b', 'c', 'd', 'e’] Most list methods are void; they modify the list and return None. >>>t.append('d','e’) Traceback (most recent call last): File "<pyshell#32>", line 1, in <module> t.append('d','e’) TypeError: append() takes exactly one argument (2 given)
  • 11. DELETING ELEMENTS pop()- This method will be used If we know the index of the element to be deleted. It modifies the list and returns the element that was removed. If we don’t provide an index, it deletes and returns the last element. >>> t = ['a', 'b', 'c’] >>> x = t.pop(1) >>> print t ['a', 'c’] >>> print x b del- If we don’t need the removed value, you can use the del operator: >>> t = ['a', 'b', 'c’] >>> del t[1] >>> print t ['a', 'c’] To remove more than one element, you can use del with a slice index: >>> t = ['a', 'b', 'c', 'd', 'e', 'f’] >>> del t[1:5] >>> print t ['a', 'f']
  • 12. remove()- If we know the element we want to remove (but not the index), you can use remove: >>> t = ['a', 'b', 'c’] >>> t.remove('b’) >>> print t ['a', 'c’] It takes exactly one argument. The return value from remove is None. insert()- It inserts an item at a specified position. >>> t = ['a', ‘c', ‘d’] >>> t.insert(1,’b’) [‘a’,’b’,’c’,’d’]
  • 13. It is important to distinguish between operations that modify lists and operations that create new lists. For example, the append method modifies a list, but >>> t1 = [1, 2] >>> t2 = t1.append(3) >>> print t1 [1, 2, 3] >>> print t2 None the + operator creates a new list: >>> t3 = t1 + [3] >>> print t3 [1, 2, 3] >>> t1 is t3 False
  • 14. LISTS AND FUNCTIONS built-in functions that can be used on lists: >>> nums = [3, 41, 12, 9, 74, 15] >>> print len(nums) 6 >>> print max(nums) 74 >>> print min(nums) 3 >>> print sum(nums) 154 >>> print sum(nums)/len(nums) 25 The sum() function only works when the list elements are numbers. The other functions (max(), len(), etc.) work with lists of strings and other types that can be comparable.
  • 15. EXAMPLES # code to find the average numbers using list functions numlist = list() while ( True ) : inp = input('Enter a number: ') if inp == 'done' : break value = float(inp) numlist.append(value) average = sum(numlist) / len(numlist) print('Average:',average) Output: Enter a number: 1 Enter a number: 2 Enter a number: 3 Enter a number: 4 Enter a number: done Average: 2.5 # Display the integers entered by the user in ascending order. data=[] # read values, adding them to the list, until the user enters 0 num = int(input("enter a number - 0 to quit:")) while num != 0: data.append(num) num = int(input("enter a number - 0 to quit:")) #sort numbers data.sort() #Display the values print("sorted numbers are") for num in data: print(num,end=" ") Output: enter number of elements to be sorted:5 enter a number50 enter a number40 enter a number20 enter a number10 enter a number30 sorted numbers are 10 20 30 40 50
  • 16. LISTS AND STRINGS list(): A string is a sequence of characters and a list is a sequence of values, but a list of characters is not the same as a string.To convert from a string to a list of characters, we can use list() method: >>> s = 'spam’ >>> t = list(s) >>> print t ['s', 'p', 'a', 'm’] The list function breaks a string into individual letters. split():If we want to break a string into words, we can use the split method: >>>txt = "welcome to the jungle" >>>x = txt.split() >>>print(x) ['welcome', 'to', 'the', 'jungle’] you can use the index operator (square bracket) to look at a particular word in the list >>>print(x[3]) jungle
  • 17. split(delimiter): You can call split with an optional argument called a delimiter that specifies which characters to use as word boundaries. The following example uses a hyphen as a delimiter: >>> s = ‘10-05-2020’ >>> s.split(‘-’) [‘10', ‘05', ‘2020’] join(): is the inverse of split. It takes a list of strings and concatenates the elements. join is a string method, so you have to invoke it on the delimiter and pass the list as a parameter: >>> t = ['pining', 'for', 'the', 'fjords’] >>> delimiter = ' ‘ >>> delimiter.join(t) 'pining for the fjords'
  • 18. #to print out the day of the week from those lines that start with “From ” fhand = open('mbox.txt') for line in fhand: line = line.rstrip() if not line.startswith('From:') : continue words = line.split() print(words[2]) Output: Sat Mon Fri mbox.txt From: stephen.marquard@uct.ac.za Sat Jan 5 09:14:16 2008 Return-Path: <postmaster@collab.sakaiproject.org> From: louis@media.berkeley.edu Mon Jan 4 16:10:39 2008 Subject: [sakai] svn commit: From: zqian@umich.edu Fri Jan 4 16:10:39 2008 Return-Path: <postmaster@collab.sakaiproject.org>
  • 19. If we execute these assignment statements: a = ‘book’ b = ‘book’ In this example, Python only created one string object, and both a and b refer to it. To check whether two variables refer to the same object, you can use the “Is” operator. >>> a = ‘book’ >>> b = ‘book’ >>> a is b True But when you create two lists, you get two objects: >>> a = [1, 2, 3] >>> b = [1, 2, 3] >>> a is b False a book b a [1, 2, 3] b [1, 2, 3] OBJECTS AND VALUES
  • 20. ALIASING An object with more than one reference has more than one name, so we say that the object is aliased. If a refers to an object and we assign b = a, then both variables refer to the same object: >>> a = [1, 2, 3] >>> b = a >>> b is a True The association of a variable with an object is called a reference. In this example, there are two references to the same object If the aliased object is mutable, changes made with one alias affect the other: >>> b[0] = 17 >>> print a [17, 2, 3]
  • 21. It is important to distinguish between operations that modify lists and operations that create new lists. For example, the append method modifies a list, but >>> t1 = [1, 2] >>> t2 = t1.append(3) >>> print t1 [1, 2, 3] >>> print t2 None the + operator creates a new list: >>> t3 = t1 + [3] >>> print t3 [1, 2, 3] >>> t2 is t3 False
  • 22. """ Exercise 8.1: Write a function called chop that takes a list and modifies it, removing the first and last elements, and returns None. Then write a function called middle that takes a list and returns a new list that contains all but the first and last elements.""" def chop(lst): del lst[0] # Removes the first element del lst[-1] # Removes the last element def middle(lst): new = lst[1:] # Stores all but the first element del new[-1] # Deletes the last element return new my_list = [1, 2, 3, 4] my_list2 = [1, 2, 3, 4] chop_list = chop(my_list) print(my_list) # Should be [2,3] print(chop_list) # Should be None middle_list = middle(my_list2) print(my_list2) # Should be unchanged print(middle_list) # Should be [2,3] Output: [2, 3] None [1, 2, 3, 4] [2, 3]