0% found this document useful (0 votes)
4 views28 pages

Module 3 Introducing List

The document provides an introduction to lists in Python, explaining their structure, how to access and manipulate elements, and methods for modifying lists such as adding, removing, and sorting items. It emphasizes the importance of index positions starting at 0 and includes practical examples and exercises for hands-on experience. Additionally, it covers common errors and methods for organizing and determining the length of lists.

Uploaded by

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

Module 3 Introducing List

The document provides an introduction to lists in Python, explaining their structure, how to access and manipulate elements, and methods for modifying lists such as adding, removing, and sorting items. It emphasizes the importance of index positions starting at 0 and includes practical examples and exercises for hands-on experience. Additionally, it covers common errors and methods for organizing and determining the length of lists.

Uploaded by

Amitabh Bose
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd

Introducing List

1
What is a list
• 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 0–9, 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
don’t have to be related in any particular way.
• In Python, square brackets ([]) indicate a list.
• Individual elements in the list are separated by commas. Here’s a
simple example of a list that contains a few kinds of bicycles:

2
• If you ask Python to print a list, Python returns its representation of
the list, including the square brackets:

3
Accessing Elements in a List
• Lists are ordered collections,
• You can access any element in a list by telling Python the position, or
index, of the item desired.
• To access an element in a list, write the name of the list followed by the
index of the item enclosed in square brackets.
• Example:

Output When we ask for a single item from the list, python returns that
element without the square brackets.
4
• You can also use the string methods on any element in this list.
• For example, you can format the element 'trek' more neatly by using the
title() method:

This example produces the same output as the preceding example except
'Trek' is capitalized.

5
Index Positions Start at 0, Not 1
• Python considers the first item in a list to be at position 0, not position 1.
• The second item in a list has an index of 1.
• Using this counting system, you can get any element you want from a list
by subtracting one from its position in the list.
• For instance, to access the fourth item in a list, you request the item at
index 3.
• The following asks for the bicycles at index 1 and index 3:

6
• Python has a special syntax for accessing the last element in a list.
• By asking for the item at index -1, Python always returns the last item
in the list

7
Using Individual Values from a List
• You can use individual values from a list just as you would any other
variable.
• For example, you can use f-strings to create a message based on a
value from a list.
• Let’s try pulling the first bicycle from the list and composing a
message using that value.

• Output:

8
Try it yourself
• Try these short programs to get some firsthand experience with Python’s
lists. You might want to create a new folder for each chapter’s exercises to
keep them organized.
• 3-1. Names: 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.
• 3-2. Greetings: Start with the list you used in Exercise 3-1, but instead of just
printing each person’s name, print a message to them. The text of each
message should be the same, but each message should be personalized
with the person’s name.
• 3-3. Your Own List: Think of your favorite mode of transportation, such as a
motorcycle or a car, and make a list that stores several examples. Use your
list to print a series of statements about these items, such as “I would like to
own a Honda motorcycle.”

9
Changing, Adding, and Removing Elements
• Modifying Elements in a List:
• The syntax for modifying an element is similar to the syntax for accessing an
element in a list.
• To change an element, use the name of the list followed by the index of the
element you want to change, and then provide the new value you want that
item to have.
• For example, let’s say we have a list of motorcycles, and the first item in the list
is 'honda'. How would we change the value of this first item?

10
• The code at 1 defines the original list, with 'honda' as the first
element.
• The code at 2 changes the value of the first item to 'ducati’.
• The output shows that the first item has indeed been changed, and
the rest of the list stays the same:

You can change the value of any item in a list, not just the first
item.

11
Adding Elements to a List
• You might want to add a new element to a list for many reasons.
• Python provides several ways to add new data to existing lists.
• Appending Elements to the End of a List:
• 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.

12
• 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() calls.
• Using an empty list, let’s add ‘honda’,’yamaha’ and ‘Suzuki’ to the list.

13
• Inserting Elements into a List:
• You can add a new element at any position in your list by using the insert()
method.
• You do this by specifying the index of the new element and the value of the
new item.

• In this example, the code at 1 inserts the value 'ducati' at the beginning of
the list.
• The insert() method opens a space at position 0 and stores the value 'ducati'
at that location.
• This operation shifts every other value in the list one position to the right:
14
Removing Elements from a List
• Often, you’ll want to remove an item or a set of items from a list.
• For example, when a player shoots down an alien from the sky, you’ll
most likely want to remove it from the list of active aliens
• Removing an Item Using the del Statement:
• If you know the position of the item you want to remove from a list, you can
use the del statement.

15
• You can remove an item from any position in a list using the del
statement if you know its index.
• For example, here’s how to remove the second item, 'yamaha', in the
list:

In both examples, you can no longer access the value that was removed from the list after
the del statement is used.

16
Removing an Item Using the pop() Method
• Sometimes you’ll want to use the value of an item after you remove it
from a list.
• For example, you might want to get the x and y position of an alien that
was just shot down, so you can draw an explosion at that position.
• In a web application, you might want to remove a user from a list of
active members and then add that user to a list of inactive members.
• The pop() method removes the last item in a list, but it lets you work
with that item after removing it.
• The term pop comes from thinking of a list as a stack of items and
popping one item off the top of the stack.
• In this analogy, the top of a stack corresponds to the end of a list.
17
• Let’s pop a motorcycle from a list of motor cycle:

• We start by defining and printing the list motorcycles at 1.


• At 2 we pop a value from the list and store that value in the variable popped_motorcycle.
• We print the list at 3 to show that a value has been removed from the list.
• Then we print the popped value at 4 to prove that we still have access to the value that was
removed.

18
Popping Items from any Position in a List
• You can use pop() to remove an item from any position in a list by
including the index of the item you want to remove in parentheses.

• We start by popping the first motorcycle in the list at 1,


• we print a message about that motorcycle at 2.
• The output is a simple sentence describing the first motorcycle I ever owned:

Output:

19
Removing an Item by Value
• Sometimes you won’t know the position of the value you want to
remove from a list.
• If you only know the value of the item you want to remove, you can
use the remove() method.
• For example, let’s say we want to remove the value 'ducati' from the
list of motorcycles.

Output :

20
Organizing a List
• Often, your lists will be created in an unpredictable order, because you
can’t always control the order in which your users provide their data.
• Although this is unavoidable in most circumstances, you’ll frequently
want to present your information in a particular order.
• Sometimes you’ll want to preserve the original order of your list.
• Other times you’ll want to change the original order.
• Python provides a number of different ways to organize your lists,
depending on the situation.

21
Sorting a List Permanently with the sort() Method
• Python’s 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, let’s assume that all the values in the list are
lowercase.

Output:

22
Sort the list in reverse order

23
Sorting list temporarily with the sorted () function

To maintain the original order of a list but present it in a sorted order, you can
use the sorted() function. It does not affect the original order of the list.

Output:

24
Sorting List temporarily in alphabetic order

Output

25
Printing a List in Reverse Order
• To reverse the original order of a list, you can use the reverse()
method.

Notice that reverse() doesn’t sort backward


alphabetically; it simply reverses the order of the list:

The reverse() method changes the order of a list permanently, but you
can revert to the original order anytime by applying reverse() to the
same list a second time.
26
Finding the Length of a List
• You can quickly find the length of a list by using the len() function. The
list in this example has four items, so its length is 4:

• You’ll find len() useful when you need to identify the number of aliens
that still need to be shot down in a game,
• determine the amount of data you have to manage in a visualization, or
• figure out the number of registered users on a website, among other
tasks.

27
Avoiding Index Errors When Working with Lists
• One type of error is common to see when you’re working with lists for
the first time.
• Let’s say you have a list with three items, and you ask for the fourth
item:

Output:

28

You might also like