In this tutorial, let’s try to solve some examples before moving to the advanced topics. Feel free to skip if you are not a beginner. In this tutorial, we will explain you how you can find max in List Python.
Table of Contents
Find Max in List Python
Lets us start with an easier one. Try to Find Max in List Python on your own.
l=[1,7,4,11,2,21] maximum_element=l[0] for i in l: if i>maximum_element: maximum_element=i print(maximum_element)
Explanation:
- Define a variable called maximum_element and assign some number to it.
- Then we are iterating through all the elements in the list.
- We are comparing each element with the maximum_element, if the element is greater than the maximum element, then we are assigning the element to the maximum_element.
Sort a list in Python
Let’s try to sort a list in the ascending order. You can try to do it the descending order.
l=[1,7,4,11,2,21] length=len(l) for i in range(length): for j in range(i,length): if l[i]>l[j]: temp=l[i] l[i]=l[j] l[j]=temp print(l)
Explanation
- The outer for loop iterates through each element in a list.
- Inner loop iterates through the list starting the element after the ith element and then continues till the last element. The reason being, we don’t need to compare the same element.
- And then we are comparing the element with all the other elements in the list.
- When we encounter a number which is lesser than i, we are swapping the element positions.
- 1 is lesser than all the elements, so there will be no changes in the order after the 1st iteration.
- For the 2nd iteration, i will be 1 and l[1] will be 7, when it counters 4 which is lesser than 7, these 2 elements will be swapped and the order will be [1,4,7,11,2,21]. Since we are referring to the index, i is still 1 but l[i] will be 4 instead of 7 due to swapping. The inner loop doesn’t stop with that, it has to continue till the end of the loop. When 2 is encountered, which is lesser than 4 and items will be swapped again. And the final order after the 2nd iteration of the outer loop will be [1,2,7,11,4,21].
- The steps will be repeated for the remaining elements.
Decimal to Binary Conversion in Python
num=17 ans='' while(num>0): ans+=str(num%2) num=num//2 print(ans[::-1])
Explanation
- We keep dividing the number until it becomes less than 1.
Exercise
- Fibonacci Series.
- Check a number is palindrome or not.
- Find if a given year is a leap year or not.
- Find the factorial number of a number.
- Check if a number is a prime number or not.
References