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

vertopal.com_Organizing a List

The document provides an overview of organizing lists in Python, including methods for sorting, reversing, and finding the length of lists. It explains the use of the sort() method for permanent sorting, the sorted() function for temporary sorting, and other list operations like reverse() and len(). Additionally, it includes exercises demonstrating these concepts with examples involving cars, mountains, rivers, and dinner guests.

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 views

vertopal.com_Organizing a List

The document provides an overview of organizing lists in Python, including methods for sorting, reversing, and finding the length of lists. It explains the use of the sort() method for permanent sorting, the sorted() function for temporary sorting, and other list operations like reverse() and len(). Additionally, it includes exercises demonstrating these concepts with examples involving cars, mountains, rivers, and dinner guests.

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/ 8

# 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,
# and 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.

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

cars = ['bmw', 'audi', 'toyota', 'subaru']


cars.sort()
print(cars)

['audi', 'bmw', 'subaru', 'toyota']

##You can also sort this list in reverse-alphabetical order by passing


the argument reverse=True to the sort() method.

cars = ['bmw', 'audi', 'toyota', 'subaru']


cars.sort(reverse=True)
print(cars)

['toyota', 'subaru', 'bmw', 'audi']

#######Sorting a 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. The sorted()
##function lets you display your list in a particular order, but
doesn’t affect the actual order of the list.

cars = ['bmw', 'audi', 'toyota', 'subaru']


print("Here is the original list:")
print(cars)
print("\nHere is the sorted list:")
print(sorted(cars))
print("\nHere is the original list again:")
print(cars)

Here is the original list:


['bmw', 'audi', 'toyota', 'subaru']

Here is the sorted list:


['audi', 'bmw', 'subaru', 'toyota']
Here is the original list again:
['bmw', 'audi', 'toyota', 'subaru']

#The sorted() function can also accept a reverse=True argument if you


want to display a list in reverse-alphabetical order.

cars = ['bmw', 'audi', 'toyota', 'subaru']


print("Here is the original list:")
print(cars)
print("\nHere is the reverse sorted list:")
print(sorted(cars, reverse=True))
print("\nHere is the original list again:")
print(cars)

Here is the original list:


['bmw', 'audi', 'toyota', 'subaru']

Here is the reverse sorted list:


['toyota', 'subaru', 'bmw', 'audi']

Here is the original list again:


['bmw', 'audi', 'toyota', 'subaru']

###Note: Sorting a list alphabetically is a bit more complicated when


all the values are not in lowercase.
# There are several ways to interpret capital letters when determining
a sort order, and specifying the exact order
# can be more complex than we want to deal with at this time. However,
most approaches to sorting will build
# directly on what you learned in this section.

#####Printing a List in Reverse Order#####

#To reverse the original order of a list, you can use the reverse()
method.

cars=['bmw', 'audi', 'toyota', 'subaru']


print(cars)
cars.reverse()
print(cars)

['bmw', 'audi', 'toyota', 'subaru']


['subaru', 'toyota', 'audi', 'bmw']

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

cars = ['bmw', 'audi', 'toyota', 'subaru', 'mercedez']


len(cars)
5

#Friends names in the list lets find out the length of list through
len() function

friends=['amir', 'omer', 'asif','satti','arsalan', 'riffat', 'majid']

friends

['amir', 'omer', 'asif', 'satti', 'arsalan', 'riffat', 'majid']

len(friends)

####EXERCISE: TO SEE THE WORLD


# List of places I'd like to visit (not in alphabetical order)
places_to_visit = ['tokyo','Beijing', 'Gilgit', 'Capetown',
'Honkkong']
# Print the list in its original order
print("Original list:")
print(places_to_visit)
# Use sorted() to print the list in alphabetical order without
modifying the original list
print("\nList in alphabetical order (using sorted()):")
print(sorted(places_to_visit))
# Show that the original list is still in its original order
print("\nOriginal list after sorted():")
print(places_to_visit)
# Use sorted() to print the list in reverse-alphabetical order without
changing the original list
print("\nList in reverse alphabetical order (using sorted() with
reverse=True):")
print(sorted(places_to_visit, reverse=True))
# Show that the original list is still in its original order
print("\nOriginal list after reverse sorted():")
print(places_to_visit)
# Use reverse() to change the order of the list
places_to_visit.reverse()
print("\nList after using reverse():")
print(places_to_visit)
# Use reverse() again to change the order of the list back to its
original order
places_to_visit.reverse()
print("\nList after reversing again:")
print(places_to_visit)
# Use sort() to change the list so it's stored in alphabetical order
places_to_visit.sort()
print("\nList after using sort() to store in alphabetical order:")
print(places_to_visit)
# Use sort() with reverse=True to change the list so it's stored in
reverse-alphabetical order
places_to_visit.sort(reverse=True)
print("\nList after using sort() to store in reverse alphabetical
order:")
print(places_to_visit)

####EXERCISE 2####
#Dinner Guests: Working with one of the programs from Exercises
#3-4 through 3-7 (pages 41–42), use len() to print a message
indicating
#the number of people you’re inviting to dinner.
# Original list of people you'd like to invite to dinner
guest_list = ["Albert Einstein", "Isaac Newton", "Ada Lovelace"]
len(guest_list)
# 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 3
# 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"]
len(guest_list)
# 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}")

### EXERCISE 4###


#title(): Used to capitalize the first letter of each mountain peak.
#append(): Adds a new mountain peak at the end of the list.
#insert(): Inserts a mountain at a specified index.
#sort(): Sorts the list in alphabetical order.
#sorted(): Returns a new list sorted in reverse alphabetical order.
#reverse(): Reverses the order of the list.
#len(): Returns the number of items in the list.
#remove(): Removes the first occurrence of a specified mountain.
#pop(): Removes and returns the last item from the list.
#del: Deletes an item at a specified index.
# Creating a list of mountain peaks
mountains = ["everest", "k2", "kangchenjunga", "lhotse", "makalu"]
# Display the list with title case for each mountain
mountains_title_case = [mountain.title() for mountain in mountains]
print("Mountains in title case:", mountains_title_case)
# Appending a new mountain peak to the list
mountains.append("cho oyu")
print("After appending a mountain:", mountains)
# Inserting a mountain at the second position
mountains.insert(1, "dhaulagiri")
print("After inserting a mountain at index 1:", mountains)
# Sorting the list alphabetically
mountains.sort()
print("Alphabetically sorted mountains:", mountains)
# Sorting the list in reverse alphabetical order using sorted() and
reverse=True
sorted_mountains_reverse = sorted(mountains, reverse=True)
print("Reverse alphabetically sorted mountains using sorted():",
sorted_mountains_reverse)
# Reversing the original list
mountains.reverse()
print("Reversed original list:", mountains)
# Displaying the length of the list
length_of_mountains = len(mountains)
print("Number of mountains in the list:", length_of_mountains)
# Removing a specific mountain from the list by name
mountains.remove("everest")
print("After removing 'Everest':", mountains)
# Popping the last mountain from the list
popped_mountain = mountains.pop()
print(f"After popping the last mountain '{popped_mountain}':",
mountains)
# Deleting a mountain at a specific position
del mountains[2]
print("After deleting the mountain at index 2:", mountains)
# Final state of the list
print("Final list of mountains:", mountains)

###Exercise 5####
# Creating a list of rivers in Pakistan
rivers = ["indus", "chenab", "ravi", "jhelum", "sindh"]
# Display the list with title case for each river
rivers_title_case = [river.title() for river in rivers]
print("Rivers in title case:", rivers_title_case)
# Appending a new river to the list
rivers.append("kabul")
print("After appending a river:", rivers)
# Inserting a river at the second position
rivers.insert(1, "sutlej")
print("After inserting a river at index 1:", rivers)
# Sorting the list alphabetically
rivers.sort()
print("Alphabetically sorted rivers:", rivers)
# Sorting the list in reverse alphabetical order using sorted() and
reverse=True
sorted_rivers_reverse = sorted(rivers, reverse=True)
print("Reverse alphabetically sorted rivers using sorted():",
sorted_rivers_reverse)
# Reversing the original list
rivers.reverse()
print("Reversed original list:", rivers)
# Displaying the length of the list
length_of_rivers = len(rivers)
print("Number of rivers in the list:", length_of_rivers)
# Removing a specific river from the list by name
rivers.remove("indus")
print("After removing 'Indus':", rivers)
# Popping the last river from the list
popped_river = rivers.pop()
print(f"After popping the last river '{popped_river}':", rivers)
# Deleting a river at a specific position
del rivers[2]
print("After deleting the river at index 2:", rivers)
# Final state of the list
print("Final list of rivers:", rivers)

####EXERCISE 6#####
# Creating a list of cars
cars = ["toyota", "honda", "ford", "bmw", "audi"]
len(cars)
# Display the list with title case for each car
cars_title_case = [car.title() for car in cars]
print("Cars in title case:", cars_title_case)
# Appending a new car to the list
cars.append("mercedes")
print("After appending a car:", cars)
# Inserting a car at the second position
cars.insert(1, "chevrolet")
print("After inserting a car at index 1:", cars)
# Sorting the list alphabetically
cars.sort()
print("Alphabetically sorted cars:", cars)
# Sorting the list in reverse alphabetical order using sorted() and
reverse=True
sorted_cars_reverse = sorted(cars, reverse=True)
print("Reverse alphabetically sorted cars using sorted():",
sorted_cars_reverse)
# Reversing the original list
cars.reverse()
print("Reversed original list:", cars)
# Displaying the length of the list
length_of_cars = len(cars)
print("Number of cars in the list:", length_of_cars)
# Removing a specific car from the list by name
cars.remove("ford")
print("After removing 'Ford':", cars)
# Popping the last car from the list
popped_car = cars.pop()
print(f"After popping the last car '{popped_car}':", cars)
# Deleting a car at a specific position
del cars[2]
print("After deleting the car at index 2:", cars)
# Final state of the list
print("Final list of cars:", cars)

#####Intentional Error, Index Error####

motorcycles = ['honda', 'yamaha', 'suzuki', 'herohonda', 'superpower',


'banelli']

print("All brands of motorcycles in Pakistan:", motorcycles)

len(motorcycles)

###Lets apply index error command


print(motorcycles[7])# this is going to give an error that list index
out of range.

print(motorcycles[-1])

print(motorcycles[-2])

print(motorcycles[-3])
print(motorcycles[2])

You might also like