[go: up one dir, main page]

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

Python Sort List. The Sort Method Is Used To Sort The Elements in A Specific Order I.E

The document discusses various advanced list methods in Python, including sorting lists in ascending and descending order using the sort() method, maintaining the original list order using the sorted() function, reversing lists using the reverse() method, finding indices of list elements using the index() method, copying lists, joining lists into strings using join(), summing list elements using sum(), removing duplicates by converting to a dictionary, and creating lists using list comprehension.
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)
44 views9 pages

Python Sort List. The Sort Method Is Used To Sort The Elements in A Specific Order I.E

The document discusses various advanced list methods in Python, including sorting lists in ascending and descending order using the sort() method, maintaining the original list order using the sorted() function, reversing lists using the reverse() method, finding indices of list elements using the index() method, copying lists, joining lists into strings using join(), summing list elements using sum(), removing duplicates by converting to a dictionary, and creating lists using list comprehension.
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

Reading in English Week 2 Day 2

Theme: Python Advanced List Methods

The concepts in Python Advanced list includes Python Sort Method, Sorted function, Python
Reverse List, Python Index Method, Copying a List, Python Join Function, Sum Function,
Removing duplicates from the List, Python List Comprehension, etc.

Python Sort List. The sort() method is used to sort the elements in a specific order i.e.
Ascending or Descending. If you want to sort the elements in Ascending order, then you
can use the following syntax.
list.sort()

If you want to sort the elements in Descending order, then you can use the following syntax.
list.sort(reverse=True)

Example:

Input:

Students = ['Harsh', 'Andrew', 'Danny']

Students.sort()

print(Students)

Output:

[‘Andrew’, ‘Danny’, ‘Harsh’]

Now let’s see, How to sort the list in a Descending Order.

Input:

Students = ['Harsh', 'Andrew', 'Danny']

“Formando líderes para la construcción de un nuevo país en paz”


Universidad de Pamplona
Pamplona - Norte de Santander - Colombia 1
Tels: (7) 5685303 - 5685304 - 5685305 - Fax: 5682750
SC-CER96940 www.unipamplona.edu.co
Students.sort(reverse=True)

print(Students)

Output:

[‘Harsh’ , Danny’ , ‘Andrew’]

Thus sort() method is used to arrange a list in either Ascending or Descending order. One
more important thing to remember here is that sort() method changes the order of the list
permanently. If you want to change the order of the list temporarily, then you need to use
sorted() function.

Sorted function. In order to maintain the original order of the list that is present in sorted
order, you can use the sorted() function. The sorted() function allows you to display your
list in a particular order, without affecting the actual order of the list.

Example:

Input:

Students = ['Harsh', 'Andrew', 'Danny']

print(sorted(Students))

print(Students)

Output:

[‘Andrew’, ‘Danny’, ‘Harsh’]


[‘Harsh’, ‘Andrew’, ‘Danny’]

As you can see from the output, the original order of the list remains intact.

You can also print the list in a reverse order using the sorted function in the following
manner:

“Formando líderes para la construcción de un nuevo país en paz”


Universidad de Pamplona
Pamplona - Norte de Santander - Colombia 2
Tels: (7) 5685303 - 5685304 - 5685305 - Fax: 5682750
SC-CER96940 www.unipamplona.edu.co
Input:

Students = ['Harsh', 'Andrew', 'Danny']

print(sorted(Students))

print(Students)

Output:

[‘Andrew’, ‘Danny’, ‘Harsh’]


[‘Harsh’, ‘Andrew’, ‘Danny’]

Python Reverse List. In order to reverse the original order of a list, you can use the reverse()
method. The reverse() method is used to reverse the sequence of the list and not to arrange
it in a sorted order like the sort() method.

Example:

Input:

Students = ['Harsh', 'Andrew', 'Danny']

Students.reverse()

print(Students)

Output:

[‘Danny’, ‘Andrew’, ‘Harsh’]

reverse() method reverses the sequence of the list permanently. Hence in order to get back
to the original sequence of the list apply the reverse() method again to the same list.

“Formando líderes para la construcción de un nuevo país en paz”


Universidad de Pamplona
Pamplona - Norte de Santander - Colombia 3
Tels: (7) 5685303 - 5685304 - 5685305 - Fax: 5682750
SC-CER96940 www.unipamplona.edu.co
Python List Index. Index method is used to find a given element in the list and return to its
position. If the same element is present more than once, then it returns the position of the
first element. The index in python starts from 0.

Example:

Input:

Students = ['Harsh','Andrew','Danny','Ritesh','Meena']

print(Students.index('Danny'))

Output:

If you search for an element which is not present in the list, then You will get an error.

Input:

Students = ['Harsh','Andrew','Danny','Ritesh','Meena']

print(Students.index('Vammy'))

Output:

Value Error: ‘Vammy’ is not in the list

“Formando líderes para la construcción de un nuevo país en paz”


Universidad de Pamplona
Pamplona - Norte de Santander - Colombia 4
Tels: (7) 5685303 - 5685304 - 5685305 - Fax: 5682750
SC-CER96940 www.unipamplona.edu.co
Python Copy List. At times, You may want to start with an existing list and make an entirely
new list based on the first one. Now, let’s explore how copying a list works and also examine
a situation where copying a list is useful. In order to copy a list, you can make a slice that
includes the complete original list by omitting the first index and the second index ([:]). This,
in turn, will tell Python to make a slice that starts at the first item and ends with the last
item, by producing a copy of the entire list.

For Example, imagine we have a list of our favorite foods and we want to make a separate
list of foods that a friend likes. This friend likes everything in our list so far, so we can create
that list by copying ours.

Input:

my_foods = ['pizza', 'falafel', 'carrot cake']

friend_foods = my_foods[:]

print("My favorite foods are:")

print(my_foods)

print("\nMy friend's favorite foods are:")

print(friend_foods)

Output:

My favorite foods are:


[‘pizza’, ‘falafel’, ‘carrot cake’]

My friend’s favorite foods are:


[‘pizza’, ‘falafel’, ‘carrot cake’]

“Formando líderes para la construcción de un nuevo país en paz”


Universidad de Pamplona
Pamplona - Norte de Santander - Colombia 5
Tels: (7) 5685303 - 5685304 - 5685305 - Fax: 5682750
SC-CER96940 www.unipamplona.edu.co
Python Join List. Python join list means concatenating a list of strings to form a string.
Sometimes it’s useful when you have to convert a list to string. For Example, convert a list
to a comma separated string to save in a file.

Let’s understand this with an Example:

Input:

my_foods = ['pizza', 'falafel', 'carrot cake']

my_foods_csv=",".join(my_foods)

print("my favorite foods are:",my_foods_csv)

Output:

my favorite foods are: pizza,falafel,carrot cake

In the above example, you can see that we have the my_foods list which we have appended
in a string variable named as my_foods_csv using the join function.

Finally, we print my_foods_csv string.

Python Sum List function. Python provides an in-built function called sum() which sums up
the numbers in the list.

Example:

Input:

numbers = [4,6,8,9,3,7,2]

Sum = sum(numbers)

print(Sum)

“Formando líderes para la construcción de un nuevo país en paz”


Universidad de Pamplona
Pamplona - Norte de Santander - Colombia 6
Tels: (7) 5685303 - 5685304 - 5685305 - Fax: 5682750
SC-CER96940 www.unipamplona.edu.co
Output:

39

In the above example, we have taken a list of numbers and using the sum function we have
added all the numbers.

Python Remove Duplicates from the List. As you know, a list can contain duplicates. But in
case, if you want to remove the duplicate from a list, how can you do it?

The simple way is to convert the list to the dictionary using the list item as keys. This will
automatically remove any duplicates as dictionaries cannot have duplicate keys and all the
items in the list will tend to appear in correct order.

Example:

Input:

numbers = [4,6,8,9,3,7,2]

Sum = sum(numbers)

print(Sum)

Output:

39

In the above example we have a list with duplicate elements and from that, we have created
a dictionary, Again we have created a list out of that dictionary, and finally, we get a list
without any duplicates.

Creating a unique list from the list having duplicate elements is another way to remove
duplicates from a list.

We can do it in the following manner:

“Formando líderes para la construcción de un nuevo país en paz”


Universidad de Pamplona
Pamplona - Norte de Santander - Colombia 7
Tels: (7) 5685303 - 5685304 - 5685305 - Fax: 5682750
SC-CER96940 www.unipamplona.edu.co
Input:

mylist = [4, 5, 6, 5, 4]

uniqueList = []

<strong>for</strong> elem in mylist:

<strong>if</strong> elem not in uniqueList:

uniqueList.append(elem)

print(uniqueList)

Output:

[4, 5, 6]

In the above example, we have created a unique list and then appended the unique items
from the list to another list.

List Comprehension. If you want to create a list which contains the squares of numbers
from 1 to 10, then you can do it using for-loop.

Example:

Input:

squares = []

<strong>for</strong> value in range(1,11):

square = value**2

squares.append(square)

print(squares)

“Formando líderes para la construcción de un nuevo país en paz”


Universidad de Pamplona
Pamplona - Norte de Santander - Colombia 8
Tels: (7) 5685303 - 5685304 - 5685305 - Fax: 5682750
SC-CER96940 www.unipamplona.edu.co
Output:

[1, 4, 9, 16, 25, 36, 49, 64, 81, 100]

The above process takes 3 to 4 lines of code. But using List comprehension it can be
accomplished in just one line of code.

Input:

squares = [value**2 <strong>for</strong> value in range(1,11)]

print(squares)

Output:

[1, 4, 9, 16, 25, 36, 49, 64, 81, 100]

In the above example, we begin with a descriptive name for the list i.e. squares. Next, we
open a set of square brackets and define the expression for the values that we want to store
in the new list. In this example, the expression value that raises the value to the second
power is **2.

Then, write a for loop to generate the numbers you want to feed into the expression and
close the square brackets. The for loop in this example is for the value in the range(1,11),
which feeds the values 1 through 10 into the expression value**2.

Note: No colon is used at the end of the for statement.

Reference: Softwaretestinghelp.com

“Formando líderes para la construcción de un nuevo país en paz”


Universidad de Pamplona
Pamplona - Norte de Santander - Colombia 9
Tels: (7) 5685303 - 5685304 - 5685305 - Fax: 5682750
SC-CER96940 www.unipamplona.edu.co

You might also like