0% found this document useful (0 votes)
68 views

Swe-102 Lab 08!

The document discusses lists in Python programming. It explains that lists can store collections of data of any size and are ordered and changeable. Various methods for creating, accessing, modifying, and manipulating lists are demonstrated through examples, including using indexes, slicing, built-in list methods like append(), insert(), remove(), and more. Exercises at the end test comprehension of lists through tasks like finding errors in code, predicting output, and writing programs to work with lists in different ways such as storing names, inviting guests to dinner, and computing squares.

Uploaded by

Hammad Qamar
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
68 views

Swe-102 Lab 08!

The document discusses lists in Python programming. It explains that lists can store collections of data of any size and are ordered and changeable. Various methods for creating, accessing, modifying, and manipulating lists are demonstrated through examples, including using indexes, slicing, built-in list methods like append(), insert(), remove(), and more. Exercises at the end test comprehension of lists through tasks like finding errors in code, predicting output, and writing programs to work with lists in different ways such as storing names, inviting guests to dinner, and computing squares.

Uploaded by

Hammad Qamar
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 6

Programming Fundamentals (SWE-102) SSUET/QR/114

LAB # 08

LISTING

OBJECTIVE
Exploring list/arrays in python programming.
THEORY

A list can store a collection of data of any size. It is a collection which is ordered and
changeable. The elements in a list are separated by commas and are enclosed by a pair
of brackets [ ].

Creating a lists:
A list is a sequence defined by the list class but also have alternative for creation of list
without built-in function.
Syntax: With Built-in function list( )
list1 = list() # Create an empty list
list2 = list([2, 3, 4]) # Create a list with elements 2, 3, 4
list3 = list(["red", "green", "blue"])#Create a list with strings
list4 = list(range(3, 6)) # Create a list with elements 3, 4, 5
list5 = list("abcd") # Create a list with characters a, b, c, d

Without Built-in Function


list1 = [] #Empty list
list2 = [2, 3, 4] #Integer type list
list3 = ["red", "green"] #String type list
list4 = [2, "three", 4] #Mixed data type list

Example:
#Create list
list_1 = ["apple", "banana", "cherry"]
#display list
print("Current List:",list_1)

Accessing items from the list:


An element in a list can be accessed through the index operator, using the following
syntax: myList[index]. List indexes are starts from 0 to len(myList)-1.
Negative indexing means beginning from the end, -1 refers to the last item, -2 refers to
the second last item etc.

1
Programming Fundamentals (SWE-102) SSUET/QR/114

Example:
myList = ["The", "earth", "revolves", "around", "sun"]
print("Postive index:",myList[4])
print("Negative index:",myList[-2])
Output:
>>> %Run task1.py
Postive index: sun
Negative index: around

List Slicing [start : end]:


The index operator allows to select an element at the specified index. The slicing
operator returns a slice of the list using the syntax list[start : end]. The slice is a sublist
from index start to index end – 1.
Example:
list1= [1,2,4,5,6,7,8]
print("Slicing 2 to 5 index:",list1[2:5])
print("Slicing before 3rd index value:",list1[:3])
print("Slicing after 3rd index value:",list1[3:])

Output:
>>> %Run task2.py
Slicing 2 to 5 index: [4, 5, 6]
Slicing before 3rd index value: [1, 2, 4]
Slicing after 3rd index value: [5, 6, 7, 8]

Modifying Elements in a List:


The syntax for modifying an element is similar to the syntax for accessing an element
in a list.
Example:
#Create a list
motorcycles = ['honda', 'yamaha', 'suzuki']
print(motorcycles)
#Modify list through indexes
motorcycles[0] = 'Swift'
print(motorcycles)
Output:
>>> %Run task3.py
['honda', 'yamaha', 'suzuki']
['Swift', 'yamaha', 'suzuki']

2
Programming Fundamentals (SWE-102) SSUET/QR/114

List Methods for Adding , Changing and Removing items:


Python has a set of built-in methods that you can use on lists/arrays.
Method Description
append( ) Adds an element at the end of the list
copy( ) Returns a copy of the list
count( ) Returns the number of elements with the specified value
index( ) Returns the index of the first element with the specified value
insert( ) Adds an element at the specified position
pop( ) Removes the element at the specified position
remove( ) Removes the first item with the specified value
reverse( ) Reverses the order of the list
sort( ) Sorts the list

EXERCISE

A. Point out the errors, if any, and paste the output also in the following Python
programs.
1. Code
Def max_list( list ):
max = list[ 0 ]
for a is in list:
elif a > max:
max = a
return max
print(max_list[1, 2, -8, 0])

Output

2. Code
motorcycles = {'honda', 'yamaha', 'suzuki'}
print(motorcycles)
del motorcycles(0)
print(motorcycles)

3
Programming Fundamentals (SWE-102) SSUET/QR/114

Output:

3. Code
Def dupe_v1(x):
y = []
for i in x:
if i not in y:
y(append(i))
return y

a = [1,2,3,4,3,2,1]
print a
print dupe_v1(a)

Output:

B. What will be the output of the following programs:


1. Code
list1= [1,2,4,5,6,7,8]
print("Negative Slicing:",list1[-4:-1])
x = [1, 2, 3, 4, 5, 6, 7, 8, 9]
print("Odd number:", x[::2])

Output

4
Programming Fundamentals (SWE-102) SSUET/QR/114

2. Code
def multiply_list(elements):
t = 1
for x in elements:
t*= x
return t
print(multiply_list([1,2,9]))

Output

3. Code
def add(x,lst=[] ):
if x not in lst:
lst.append(x)
return lst

def main():
list1 = add(2)
print(list1)
list2 = add(3, [11, 12, 13, 14])
print(list2)
main()

Output

C. Write Python programs for the following:

1. Write a program that store the names of a few of your friends in a list called ‘names’.
Print each person’s name by accessing each element in the list, one at a time.
2. Write a program that make a list that includes at least four people you’d like to invite
to dinner. Then use your list to print a message to each person, inviting them to dinner.
But one of your guest can’t make the dinner, so you need to send out a new set of
invitations. Delete that person on your list, use del statement and add one more person
at the same specified index, use the insert( ) method. Resend the invitation.

5
Programming Fundamentals (SWE-102) SSUET/QR/114

3. Write a program that take list = [30, 1, 2, 1, 0], what is the list after applying each of
the following statements? Assume that each line of code is independent.
 list.append(40)
 list.remove(1)
 list.pop(1)
 list.pop()
 list.sort()
 list.reverse()

4. Write a program to define a function called ‘printsquare’ with no parameter, take


first 7 integer values and compute their square and stored all square values in the list.

You might also like

pFad - Phonifier reborn

Pfad - The Proxy pFad of © 2024 Garber Painting. All rights reserved.

Note: This service is not intended for secure transactions such as banking, social media, email, or purchasing. Use at your own risk. We assume no liability whatsoever for broken pages.


Alternative Proxies:

Alternative Proxy

pFad Proxy

pFad v3 Proxy

pFad v4 Proxy