0% found this document useful (0 votes)
3 views9 pages

Lists Basics

The document provides an overview of lists in Python, explaining how to create, access, modify, and remove elements from lists. It includes examples of using lists for various purposes, such as storing names, vehicles, and guest lists, along with exercises to practice these concepts. Additionally, it covers methods like append(), insert(), pop(), and remove() for managing list elements.

Uploaded by

Rasheal Mehdi
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)
3 views9 pages

Lists Basics

The document provides an overview of lists in Python, explaining how to create, access, modify, and remove elements from lists. It includes examples of using lists for various purposes, such as storing names, vehicles, and guest lists, along with exercises to practice these concepts. Additionally, it covers methods like append(), insert(), pop(), and remove() for managing list elements.

Uploaded by

Rasheal Mehdi
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
You are on page 1/ 9

# Lists allow you to store sets of information in one place, whether

you have just a few items or millions of items


# 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 to 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.
# A list usually contains more than one element, it’s a good idea to
# make the name of your list plural, such as letters, digits, or
names.
#In Python, square brackets ([]) indicate a list, and individual
elements in the list are separated by commas

bicycles = ['trek', 'cannondale', 'redline', 'specialized', 'BMX' ]

print(bicycles)

['trek', 'cannondale', 'redline', 'specialized', 'BMX']

#If you ask Python to print a list, Python returns its


#representation of the list, including the square brackets:
#Because this isn’t the output you want your users to see, let’s learn
how to access the individual items in a list.

########Accessing Elements in the List########

bicycles = ['trek', 'cannondale', 'redline', 'specialized', 'BMX']

print(bicycles[0])

print(bicycles[1])

print(bicycles[2])

print(bicycles[3])
print(bicycles[4])

print(bicycles[4])

##can index returns the items from the last, for that you need to use
"-2", "-3"
#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.

print(bicycles[-1])
print(bicycles[-2])
print(bicycles[-3])
print(bicycles[-4])
print(bicycles[-5])
BMX
specialized
redline
cannondale
trek

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

bicycles = ['trek', 'cannondale', 'redline','specialized', 'BMX']

message = f"My first bicycle was a {bicycles[4].title()}."

print(message)

My first bicycle was a Bmx.

####Exercise####
###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.

friends =['imran', 'Awaad', 'Tanveer', 'Amaan']


message=f"The most helpful among all is {friends[2].title()}"
print(message)

The most helpful among all is Tanveer

###Exercise 2####
teambravo=['haseeb', 'jamal', 'haider', 'mustafa']
message=f"Greetings {teambravo [-2].title()}"
print(message)

Greetings Haider

##But this is only returning me one team member name, I want to send
the greeting message to all.

teambravo=['haseeb', 'jamal', 'haider', 'mustafa']


for member in teambravo:
print(f"Greetings, {member.capitalize()}! Welcome to the team.")

Greetings, Haseeb! Welcome to the team.


Greetings, Jamal! Welcome to the team.
Greetings, Haider! Welcome to the team.
Greetings, Mustafa! Welcome to the team.
###lets give this another message to all team members
teambravo = ['haseeb', 'jamal', 'haider', 'mustafa']
for member in teambravo:
message = f"Hi {member.capitalize()}, I hope you're having a great
day! Keep up the good work."
print(message)
####capitalize() function to call the names of all members

Hi Haseeb, I hope you're having a great day! Keep up the good work.
Hi Jamal, I hope you're having a great day! Keep up the good work.
Hi Haider, I hope you're having a great day! Keep up the good work.
Hi Mustafa, I hope you're having a great day! Keep up the good work.

###Exercise 3##
#Think of your favorite mode of transportation, such as 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 .”
cars = ['Tesla', 'BMW', 'Audi', 'Mercedes']
for car in cars:
print(f"I would like to own a {car}.")
###I need a specific car out of all list###you can access Index
cars = ['Tesla', 'BMW', 'Audi', 'Mercedes']
# Suppose you want the second car in the list (BMW)
specific_car = cars[1]
print(f"I would like to own a {specific_car}.")
#Searching for a specific car
#If you don't know the index but you know the car's name, you can
search for it in the list.
cars = ['Tesla', 'BMW', 'Audi', 'Mercedes']
# Suppose you want to find 'Audi' in the list
specific_car = 'Audi'
if specific_car in cars:
print(f"I would like to own a {specific_car}.")
else:
print(f"{specific_car} is not in the list.")

I would like to own a Tesla.


I would like to own a BMW.
I would like to own a Audi.
I would like to own a Mercedes.
I would like to own a BMW.
I would like to own a Audi.

#Modifying, Adding, and Removing Elements


motorcycles = ['honda', 'yamaha', 'suzuki']
print(motorcycles)
motorcycles[0] = 'ducati'
print(motorcycles)
##Add new Elements in the 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.
motorcycles = ['honda', 'yamaha', 'suzuki']
print(motorcycles)
motorcycles.append('ducati')
print(motorcycles)

['honda', 'yamaha', 'suzuki']


['honda', 'yamaha', 'suzuki', 'ducati']

#The append() method adds 'ducati' to the end of the list


#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 the elements 'honda', 'yamaha',
#and 'suzuki' to the list.
motorcycles = []
motorcycles.append('honda')
motorcycles.append('yamaha')
motorcycles.append('suzuki')
print(motorcycles)
###Inserting Elements into list through insert()
motorcycles = ['honda', 'yamaha', 'suzuki']
motorcycles.insert(0, 'ducati')
print(motorcycles)
####can this operation shifts every other value in the list one
position to the right.
motorcycles = ['honda', 'yamaha', 'suzuki']
motorcycles.insert(3, 'ducati')
print(motorcycles)

#####Removing Elements from a List#####


#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.
# Or when a user decides to cancel their account on a web application
you created,
# you’ll want to remove that user from the list of active users.
# You can remove an item according to its position in the list or
according to its value.

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

motorcycles = ['honda', 'yamaha', 'suzuki']


print(motorcycles)
del motorcycles[0]
print(motorcycles)

['honda', 'yamaha', 'suzuki']


['yamaha', 'suzuki']

## We have just witnessed how 'honda' is removed from the list


## We use the del statement to remove the first item
motorcycles = ['honda', 'yamaha', 'suzuki']
print(motorcycles)
del motorcycles [1]
print (motorcycles)
###Note: In both examples, you can no longer access the value that was
removed from the list after the del statement is used.
##

['honda', 'yamaha', 'suzuki']


['honda', 'suzuki']

##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.
#Let’s pop a motorcycle from the list of motorcycles:

motorcycles = ['honda', 'yamaha', 'suzuki']


print(motorcycles)
popped_motorcycle = motorcycles.pop()
print(motorcycles)
print(popped_motorcycle)

['honda', 'yamaha', 'suzuki']


['honda', 'yamaha']
suzuki

##How might this pop() method be useful? Imagine that the motorcycles
in the list are stored in chronological order,
#according to when we owned them. If this is the case, we can
#use the pop() method to print a statement about the last motorcycle
we bought:
motorcycles = ['honda', 'yamaha', 'suzuki']
last_owned = motorcycles.pop()
print(f"The last motorcycle I owned was a {last_owned.title()}.")
#output: The output is a simple sentence about the most recent
motorcycle we owned:

###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
motorcycles = ['honda', 'yamaha', 'suzuki']
first_owned = motorcycles.pop(0)
print(f"The first motorcycle I owned was a {first_owned.title()}.")

###Removing an item by a 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, say we want to remove the value 'ducati' from the list
of motorcycles:

motorcycles = ['honda', 'yamaha', 'suzuki','ducati']


print(motorcycles)
motorcycles.remove('ducati')
print(motorcycles)

['honda', 'yamaha', 'suzuki', 'ducati']


['honda', 'yamaha', 'suzuki']

##Here the remove() method tells Python to figure out where 'ducati'
appears in the list and remove that element
#You can also use the remove() method to work with a value that’s
being removed from a list. Let’s remove the value
#'ducati' and print a reason for removing it from the list:

motorcycles = ['honda', 'yamaha', 'suzuki','ducati']


print(motorcycles)
too_expensive = 'ducati'
motorcycles.remove(too_expensive)
print(motorcycles)
print(f"\n\tA {too_expensive.title()} is too expensive for me.")

['honda', 'yamaha', 'suzuki', 'ducati']


['honda', 'yamaha', 'suzuki']

A Ducati is too expensive for me.

#NOTE:
#The remove() method deletes only the first occurrence
#of the value you specify. If there’s a possibility the value
#appears more than once in the list, you’ll need to use a
#loop to make sure all occurrences of the value are
#removed.
# Example : Guest List
# Guest List: If you could invite anyone, living or deceased, to
dinner, who would you invite?
# Make a list that includes at least three people you’d like to
invite to dinner.
# Then use your list to print a message to each person, inviting them
to dinner.
# List of people you'd like to invite to dinner

guest_list = ["Albert Einstein", "Marie Curie", "Ada Lovelace"]


# Loop through the list and print an invitation message for each
person
for guest in guest_list:
print(f"Dear {guest},")
print("I would be honored to have you join me for dinner.")
print("Looking forward to an evening of great conversation!\n")

#Now, You just heard that one of your guests can’t make the dinner, so
you need to send out a new set of invitations.
# You’ll have to think of someone else to invite.
#Start with your program from prevous exercise. Add a print() call at
the end
# of your program, stating the name of the guest who can’t make it.
# Modify your list, replacing the name of the guest who can’t make it
with the name of the new person you are inviting.
#Print a second set of invitation messages, one for each person who is
still in your list.
# Original list of people you'd like to invite to dinner

guest_list = ["Albert Einstein", "Marie Curie", "Ada Lovelace"]

# One guest can't make it


unable_to_attend = guest_list[1]
print(f"Unfortunately, {unable_to_attend} can't make it to the
dinner.\n")

Unfortunately, Marie Curie can't make it to the dinner.

# Replace the guest who can't make it with a new guest


guest_list[1] = "Isaac Newton"

# Print the second set of invitation messages


for guest in guest_list:
print(f"Dear {guest},")
print("I would be honored to have you join me for dinner.")
print("Looking forward to an evening of great conversation!\n")

Dear Albert Einstein,


I would be honored to have you join me for dinner.
Looking forward to an evening of great conversation!
Dear Isaac Newton,
I would be honored to have you join me for dinner.
Looking forward to an evening of great conversation!

Dear Ada Lovelace,


I would be honored to have you join me for dinner.
Looking forward to an evening of great conversation!

#Exercise 3
#More Guests: You just found a bigger dinner table, so now more
#space is available. Think of three more guests to invite to dinner.
#Start with your program from previous exercises. Add a print() call
to
#the end of your program, informing people that you found a bigger
table.
#Use insert() to add one new guest to the beginning of your list.
#Use insert() to add one new guest to the middle of your list.
#Use append() to add one new guest to the end of your list.
#Print a new set of invitation messages, one for each person in your
list.

# Original list of people you'd like to invite to dinner


guest_list = ["Albert Einstein", "Isaac Newton", "Ada Lovelace"]

# Inform about the bigger table


print("Good news! I just found a bigger dinner table, so I can invite
more guests!\n")

# Add three more guests


guest_list.insert(0, "Nikola Tesla") # Add to the beginning
guest_list.insert(2, "Galileo Galilei") # Add to the middle
guest_list.append("Leonardo da Vinci") # Add to the end

print(guest_list)

# Print the new set of invitation messages


for guest in guest_list:
print(f"Dear {guest},")
print("I would be honored to have you join me for dinner.")
print("Looking forward to an evening of great conversation!\n")

#Exercise
#Shrinking Guest List: You just found out that your new dinner table
won’t arrive in time for the dinner,
# and now you have space for only two guests.
#Start with your program from Previous exercise. Add a new line that
prints a
#message saying that you can invite only two people for dinner.
#Use pop() to remove guests from your list one at a time until only
two
#names remain in your list. Each time you pop a name from your list,
#print a message to that person letting them know you’re sorry you
can’t
#invite them to dinner.
#Print a message to each of the two people still on your list, letting
them know they’re still invited.
#Use del to remove the last two names from your list, so you have
anempty list.
#Print your list to make sure you actually have an empty list at the
end of your program.

# Current list of people you'd like to invite to dinner


guest_list = ["Nikola Tesla", "Albert Einstein", "Galileo Galilei",
"Isaac Newton", "Ada Lovelace", "Leonardo da Vinci"]

# Inform about the change of plans


print("Unfortunately, the new dinner table won't arrive in time, so I
can only invite two people for dinner.\n")

# Remove guests until only two remain, apologizing to each


while len(guest_list) > 2:
removed_guest = guest_list.pop()
print(f"Sorry {removed_guest}, but I can't invite you to dinner
this time.\n")

# Print messages to the remaining two guests


for guest in guest_list:
print(f"Dear {guest},")
print("You are still invited to the dinner! Looking forward to
seeing you.\n")

# Remove the last two guests


del guest_list[0]
del guest_list[0]

# Print the list to confirm it's empty


print(f"Final guest list: {guest_list}")

You might also like