Welcome to our next tutorial of Python 3. Previously, we covered the fundamentals of Python 3, and today, we will explore lists. In case you are looking for an excellent book to learn Python, then do check out this recommended list.
Lists are simply a way to store data in Python programs which is quite similar to arrays in other programming languages. The critical difference is that in lists, we can store different types of data. For example, you can store strings, numerals, and boolean values which is not supported by arrays in C, C++, C#, and other programming languages.
Also Read: Dictionary In Python 3 | Learn With Examples.
What you will learn in this tutorial.
- How to create lists in Python 3?
- Characteristics of Python 3 lists
- Reading data through lists
- Negative Indexing
- Slicing lists
- Most frequently used Python 3 list functions.
If you are not interested in theory and want to learn how to work with lists with hands-on programming, then jump to this section and start learning by examples. However, if you are just getting started with Python programming, then I will recommend you to go through the tutorial in this order.
How to create lists in Python 3?
Here’s how you define a list.
students = ['Himanshu', 'Harsh', 'Sanjeev', 25, 21, 25]
Characteristics of Python 3 lists
- Lists are mutable and dynamic
- Lists are ordered
- Lists can include any arbitrary objects
- Lists can include lists as data elements
- Lists can be nested to any level
Reading/Traversing data through lists
There are numerous ways to read or traverse data through lists. Here we will explore the most common ones used.
A. Using for loop
Ages = [23, 34, 45, 36] for x in Ages: print(x)
B. Using for and range
Ages = [23, 34, 45, 36] size = len(Ages) for x in range(size): print(Ages[x])
C. List comprehensions
Numbers = [23, 34, 43, 67] [print(i) for i in Numbers]
We will explore list comprehensions in future, as it requires a complete article in itself.
Negative indexing
Usually, we count the indexes of list elements from the left, i.e., from the starting. With negative indexing, you can count the indexes of list elements from the right or begin the counting from the end.
Numbers = [23, 34, 43, 67] print(Numbers[-2])
As in this example, we are referring to the second last element of the list Ages.
Slicing lists
Slicing is a Pythonic concept which allows you to obtain sub-elements from a list, tuple or any other data structure without using a for-loop.
Here’s how slicing works for Python 3 lists.
Numbers = [23, 34, 43, 67] print(Numbers[1:4])
In the code above, Numbers[1:4] means that we want to get the elements from 2nd position (Index = 1) to end of the 5th element but not include it.
Most frequently used Python 3 list functions.
- Clear() – It removes all the elements from a list.
- Copy() – Returns a copy of this list.
- Insert() – Adds an element at a specified location in the list.
- Remove() – Remove the first element with a specific value from the list.
- Pop() – Remove an element at the specified position.
- Count() – Returns the total number of occurrences of a specified element.
- Sort() – Arranges the list in ascending order by default. You can also use it to arrange the list in descending order.
- Reverse() – It reverses the order of a list.
- Extend() – Add elements of a list or any other iterable to the end of the current list.
- Append() – This list function adds an element at the end of this list.
Let’s now see some Python programs to understand lists better. In case, there are any issues, please leave the comment, and I will be more than happy to assist you.
1. Python program to interchange first and last elements in a list
ageList =[21, 98, 34, 56, 65] def swapElements(ageList): size = len(ageList) #Swapping logic temp = ageList[0] ageList[0]=ageList[size-1] ageList[size-1]=temp return ageList print(swapElements(ageList))
Output:
[65, 98, 34, 56, 21]
2. Python program to swap two elements in a list
ageList =[21, 98, 34, 56, 65] firstPos = 1 secondPos = 2 def swapElements(ageList, firstPos, secondPos): #Swapping logic ageList[firstPos], ageList[secondPos] = ageList[secondPos], ageList[firstPos] return ageList print(swapElements(ageList,firstPos, secondPos))
Output:
[21, 34, 98, 56, 65]
3. Python program to remove Nth occurrence of the given word
names = ['Himanshu', 'Harsh', 'Vivek', 'Abhishek'] elementPos = int(input('Enter element position to delete')) def deleteElement(names, elementPos): del(names[elementPos]) return names print(deleteElement(names, elementPos))
Output:
Enter element position to delete 2
[‘Himanshu’, ‘Harsh’, ‘Abhishek’]
4. Python program to check if element exists in the list
Ages = [21, 23, 43, 45, 67, 78, 98, 99] elementPos = int(input('Enter element to search: ')) def searchElement(Ages, elementPos): size = len(Ages) for k in range(size-1): if elementPos == Ages[k]: return k k = searchElement(Ages, elementPos) print("The Element found at ", k+1)
Output:
Enter element to search: 67
The Element found at 5
5. Python program to reverse a List
To reverse a list in Python 3, we can use the reverse() function. It is a built-in function that reverses a list without creating a new one as it modifies the content of the original list.
Here’s an example.
Ages = ['23', '45', '65', '89', '34'] Ages.reverse() size = len(Ages) for i in range(size-1): print(Ages[i])
Output:
34
89
65
45
6. Python program to clone or copy a list
To clone or copy a list in Python 3, you can again use an in-built function called copy() which returns a copy of the list.
Here’s how you can use this Python 3 function.
Ages = ['23', '45', '65', '89', '34'] copyAges = Ages.copy() print(copyAges)
Output:
[’23’, ’45’, ’65’, ’89’, ’34’]
7. Python program to count occurrences of an element in a list
Scores = [100, 200, 300, 100, 200, 300, 100, 100] countElement = int(input("Enter an element to search ")) def countOccurence(Scores, countElement): count = 0 size = len(Scores) for i in range(size-1): if countElement == Scores[i]: count = count + 1 if count ==0: print("No element found") return count count = countOccurence(Scores, countElement) print("Number of times element occurs in the list = ", count)
Output:
Enter an element to search 100
Number of times element occurs in the list = 3
8. Python program to find the sum of elements in the list
Scores = [100, 200, 300, 230, 167, 456, 768] def sumElements(Scores): size = len(Scores) sum = 0 for i in range(size-1): sum = sum + Scores[i] return sum sum = sumElements(Scores) print("Sum of elements in a list =", sum)
Output:
Sum of elements in a list = 1453
9. Python program to multiply all numbers in the list
Scores = [1, 2, 3, 2, 1, 4] def mulElements(Scores): total = 1 for i in Scores: total *= i return total mul = mulElements(Scores) print("Multiplications of all elements in the list =", mul)
Output:
Multiplications of all elements in the list = 48
10. Python program to find the smallest number in a list
To find the smallest number in a list, we use the in-built sort function. Using sort() function, we can arrange list either in ascending or descending order.
By default, the sort method arranges all the elements in ascending order. Thus, after sorting the list, we can get the smallest number at the first index.
Here’s the code.
Ages = [23, 56, 89, 5, 4, 54, 98, 70] Ages.sort() print(Ages[0])
Output:
4
Other Python programs:
- Python 3 Program To Add Two Matrices.
- Python 3 Program to Check Armstrong Number.
- Python 3 Program to Check Leap Year.
- Python 3 Program To Check If Number Is Positive Or Negative.
- Python 3 Program to Generate A Random Number.
11. Python program to find the largest number in a list
Ages = [23, 56, 89, 5, 4, 54] size = len(Ages) Ages.sort() print(Ages[size-1])
Output:
89
12. Python program to find the second largest number in a list
Ages = [23, 56, 89, 5, 4, 54] size = len(Ages) Ages.sort() print(Ages[size-2])
Output:
56
13. Python program to find N largest element from a list
Ages = [23, 34, 45, 56, 78, 89, 34, 56, 67, 90, 100] Ages.sort() nLarge = int(input("Enter N largest number to find ")) def nlargenumber(Ages, nLarge): size = len(Ages) return Ages[size-nLarge] nLargeNumber = nlargenumber(Ages, nLarge) print(nLargeNumber)
Output:
Enter N largest number to find 3
89
14. Python program to print even numbers in a list
Ages = [23, 34, 45, 56, 78, 89, 34, 56, 67, 90, 100] def even(Ages): size = len(Ages) for i in range(size): if Ages[i]%2 == 0: print(Ages[i]) even(Ages)
Output:
34
56
78
34
56
90
100
15. Python program to print odd numbers in a List
Ages = [23, 34, 45, 56, 78, 89, 34, 56, 67, 90, 100] def even(Ages): size = len(Ages) for i in range(size): if Ages[i]%2 != 0: print(Ages[i]) even(Ages)
Output:
23
45
89
67
Summing Up
In this Python 3 tutorial, you learn how to work with lists. In our next tutorial, we will explore tuples. If you have any queries or issues, then do leave a comment and I will try to assist you. You can also send your suggestions at [email protected].
Subscribe to our newsletter to receive all the latest updates straight to your inbox.
Other Python tutorials you can check out:
- How To Make A Simple Python 3 Calculator Using Functions.
- How To Use Python For Browser Games Development?
- Sending Emails Using Python With Image And PDF Attachments.
Hello Friends! I am Himanshu, a hobbyist programmer, tech enthusiast, and digital content creator.
With CodeItBro, my mission is to promote coding and help people from non-tech backgrounds to learn this modern-age skill!