Python Advanced List Tutorial (List Sort, Reverse, Index, Copy, Join, Sum)

Python Advanced List Methods with Examples:

In this tutorial, we will explore some of the Advanced concepts in Python list.

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.

Read through our Free Python Guide for beginners to gain immense knowledge on Python concept. Python Advanced List Tutorial

Python Advanced List includes the following concepts.

Let's explore each of them in detail with examples.

#1) 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']
Students.sort()
print(Students)

Output:

[‘Andrew', ‘Danny', ‘Harsh']

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.

#2) 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:

Input:

Students = ['Harsh', 'Andrew', 'Danny']
print(sorted(Students))
print(Students)

Output:

[‘Andrew', ‘Danny', ‘Harsh']
[‘Harsh', ‘Andrew', ‘Danny']

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

#4) 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:

2

Screenshot: 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

#5) 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']

Screenshot: First, we create a list of the foods we like called my_foods. Then we make a new list called friend_foods. Later, we make a copy of my_foods by asking for a slice of my_foods without specifying any indices and store the copy in friend_foods. When we print each list, we see that they both contain the same foods.

To prove that we actually have two separate lists, we’ll add new food to each list and show that each list keeps track of the appropriate person’s favorite foods:

Input:

my_foods = ['pizza', 'falafel', 'carrot cake']
my_foods.append('cannoli')
friend_foods.append('ice cream')
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', ‘cannoli', ‘ice cream']

My friend's favorite foods are:
[‘pizza', ‘falafel', ‘carrot cake', ‘cannoli', ‘ice cream']

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

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

Output:

39

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

#8) 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:

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.

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

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.

Sample Programs

Write a program to sort the list of cricket players according to their names.

#Create a List
Cricket_Players = ['Sourav', 'Rahul','Sachin','Mahender','Virat','Shikhar','Harbhajan']

#Print Original List
print("Original List:")
print(Cricket_Players)

#Sort the List
Cricket_Players.sort()

#Print Sorted List
print("Sorted List:")
print(Cricket_Players)

Write a program to reverse the list of cell phone vendors.

#Create a List
CellPhone_Vendors = ['Nokia','Samsung','Xiomi','Apple','Motorola']

#Print Original List
print("Original List:")
print(CellPhone_Vendors)

#Reverse the List
CellPhone_Vendors.reverse()

#Print Reversed List
print("Reversed List:")
print(CellPhone_Vendors)

Write a program to remove duplicates from the list of students participating in the sports day.

#Create a List
Student_Players = ['Reyan','Vicky','Mark','Steve','Mark','Reyan','Vijay']

#Print Original List
print("Original List:")
print(Student_Players)

#Create an empty list
unique_List=[]

#Append unique elements from list to empty list
<strong>for</strong> student in Student_Players:
<strong>if</strong> student not in unique_List:
unique_List.append(student)

#Print new list
print("Unique List:")
print(unique_List)

Write a program to demonstrate sort, reverse and finding the index of the element in a list containing numbers.

#Create a Sorted list
my_list = [7, 8, 3, 6, 2, 8, 4]

#Find the index of element in a list
print(my_list.index(8))

#Sort the list
my_list.sort()

#Print the sorted list
print(my_list)

#Reverse the list
my_list.reverse()

#Print the reversed list
print(my_list)

Conclusion

From this tutorial, we learned how to perform various operations on a list using different methods and functions.

We can conclude this tutorial using the below pointers:

• Sort method is used to sort the list permanently.
• The sorted function is used to present the list in sorted order. However, the original sequence of the list remains unchanged.
• Reverse method is used to reverse the order of the list.
• Sum() function is used to sum the elements in the list.
• You can remove the duplicate elements in the list by converting a list to a dictionary or by creating a new list and using for loop and if condition to append only the unique elements.
• List comprehension can be used to reduce the lines of code to create a specific type of list.