Sie sind auf Seite 1von 8

Lists & Control Flow Statements SSUET/QR/114

LAB # 03
LISTING IN PYTHON LANGUAGE
OBJECTIVE
To learn about listing in Python and study about how to change, add and remove any
item in a list using different functions.

THEORY
3.1 Lists:
A list is a collection of items in a particular order. You can make a list that includes the letters of
the alphabet, the digits from 09, or the names of all the people in your family. You can put
anything you want into a list, and the items in your list dont have to be related in any particular
way. Because a list usually contains more than one element, its a good idea to make the name of
your list plural, such as letters, digits, or names.
It can have any number of items and they may be of different types (integer, float, string etc.). In
Python, square brackets ([]) indicate a list, and individual elements in the list are separated by
commas.
# empty list
my_list = []
# list of integers
my_list = [1, 2, 3]
# list with mixed datatypes
my_list = [1, "Hello", 3.4]
Also, a list can even have another list as an item. This is called nested list.
# nested list
my_list = ["mouse", [8, 4, 6], ['a']]
Some simple example of a list:

16
Lists & Control Flow Statements SSUET/QR/114

Heres a simple example of a list thatcontains a few kinds of bicycles:

Example#01:
bicycles = ['trek', 'cannondale', 'redline', 'specialized']
print(bicycles)
If you ask Python to print a list, Python returns its representation of the list, including the square
brackets:

Output:
['trek', 'cannondale', 'redline', 'specialized']

3.1.1 Accessing Values in Lists:


To access values in lists, use the square brackets for slicing along with the index or indices to
obtain value available at that index.
Example#02:

Python considers the first item in a list to be at position 0, not position 1. This is true of
most programming languages, and the reason has to do with how the list operations are
implemented at a lower level. If youre receiving unexpected results, determine whether
you are making a simple off-by-one error. The second item in a list has an index of 1. Using

17
Lists & Control Flow Statements SSUET/QR/114

this simple counting system, you can get any element you want from a list by subtracting
one from its position in the list.
This convention extends to other negative index values as well. The index -2 returns the
second item from the end of the list,the index -3 returns the third item from the end, and
so forth.

3.2 Changing, Adding, and Removing Elements


Most lists you create will be dynamic, meaning youll build a list and then add and remove
elements from it as your program runs its course.

3.2.1 Modifying Elements in a List:


The syntax for modifying an element is similar to the syntax for accessingan element in a list. To
change an element, use the name of the list followedby the index of the element you want to
change, and then provide the newvalue you want that item to have.For example, lets say we
have a list of motorcycles, and the first item inthe list is 'honda'. How would we change the value
of this first item?

Example#03:

Output:

3.2.2 Adding/Appending Elements to a List:


You might want to add a new element to a list for many reasons. For example, you might want to
make new aliens appear in a game, add new data to a visualization, or add new registered users
to a website youve built. Python provides several ways to add new data to existing lists.

The simplest way to add a new element to a list is to append the item to the list. When you
append an item to a list, the new element is added to the end of the list. Using the same list we
had in the previous example, well add the new element 'ducati' to the end of the list:

Example#04:

18
Lists & Control Flow Statements SSUET/QR/114

The append() method , adds 'ducati' to the end of the list without affecting any of the other
elements in the list:
Output:

The append() method makes it easy to build lists dynamically. For example, you can start with an
empty list and then add items to the list using a series of append() statements. Using an empty
list, lets add the elements 'honda', 'yamaha', and 'suzuki' to the list:

Example#05:

Output:

3.2.3Removing Elements from a List:


Remove an item or a set of items from a list using different function like remove(),del() etc. For
example using remove(),You can remove an item according to its position in the list or according
to its value.

Example#06:

Output:

19
Lists & Control Flow Statements SSUET/QR/114

The remove operation on a list is given a value to remove. It searches the list to find an
item with that value and deletes the first matching item it finds. It is an error if there is no
matching item.

The del statement can be used to delete an entire list. If you have a specific list item as
your argument to del. It is even possible to delete a "slice" from a list.

3.3 Organizing a List:


Python provides a number of different ways to organize your lists, depending on the situation.

Sorting a List Permanently with the sort() Method:


Pythons sort() method makes it relatively easy to sort a list. Imagine we have a list of cars and
want to change the order of the list to store them alphabetically. To keep the task simple, lets
assume that all the values in the list are lowercase.

Example#07:

Output:

20
Lists & Control Flow Statements SSUET/QR/114

Lab Exercise:
Task 1
Using list bicycles = ['trek', 'cannondale', 'redline', 'specialized'], display the output as follows
about the first bicycle in the list:
My first bicycle was a Trek.

Source Code
#2014-SE-130
bicycles=["trek","cannondale","redline","specialized"]
print(bicycles)
x=int(input("Enter the index position of your bicycle: "))
x=bicycles[x-1]
print("My first bicycle was a "+x.title())

Output

Task 2
Write a script that takes persons name as input in a list in which you can add a new element at
any specified index position by using the insert() method.

Source Code
#2014-SE-130
names=[]
x=int(input("Enter number of names you wish to enter: "))
for i in range(x):
name=(input("Enter name: "))
pos=int(input("Enter index position: "))
names.insert(pos+1,name)
print(names)

Output

21
Lists & Control Flow Statements SSUET/QR/114

Task 3
Using example#6, remove last element in the list but do not use remove().
Use the del statement, del statement is similar to remove().

Source Code
#2014-SE-130
names=["abc","def","ghi","jkl","mno"]
print(names)
del (names[4])
print(names)

Output

Task 4
Using example#7, sort the list of cars in reverse alphabetical order.

Source Code
#2014-SE-130
cars=["bmw","audi","toyota","subaru"]
print(cars)
cars.sort(reverse=True)
print(cars)

Output

Task 5
Write a python script to find the length of a two lists using len().

Source Code
#2014-SE-130
x=["a","b","c","d","e"]
y=["f","g","h"]
print(x)
print(y)
print("Length of List 1 is:" ,len(x))
print("Length of List 2 is:" ,len(y))

22
Lists & Control Flow Statements SSUET/QR/114

Output

Task 6
Write a python script that take two embedded list and make it one by concatenation.

Source Code
#2014-SE-130
x=["a","b","c","d","e"]
y=["f","g","h"]
print(x)
print(y)
print(x+y)

Output

23

Das könnte Ihnen auch gefallen