The Python List is one of the most useful sequences in real-time. A Python list is a sequence of multiple values in an ordered sequence. Unlike Strings, Python List allows us to store different types of data such as integer, float, string, etc.
The following are examples of declaring a Python list of different data types.
Declare Python Lists
There are several ways to create a List in Python. The most straightforward way is to place the required list items within a square bracket [ ]
A list that contains no values or elements is an empty list. By placing an empty square bracket create an empty list.
List_Name = []
The first statement is an integer list of five integer values. The second statement is a string list that contains three String values or three words.
Integer_List = [1, 2, 3, 4, 5] String_List = ['apple', 'Orange', 'Grape', 'Mango']
Python lists allow placing different data types in a single list. The following one is an example of a mixed list, which contains one integer, float, and two integer values.
Mixed_List = ['apple', 2, 3.50, 'Mango']
How to access Python List items?
Lists sequentially store data (ordered list). So, we can access the list elements with the help of indexes. Moreover, using indexes, we can access or alter/change each item present in the Lists separately. The syntax to access List items is
List_Name([Index_Number])
Index value starts at 0 and ends at n-1, where n is the list size. For example, if a list stores 5 elements, the index starts at 0 and ends with 4. To access or alter the first list value, use list_name[0], and to access the fifth list item, use list_name[4]. Let’s see the list example for better understanding:
x = [1, 2, 3, 4, 5, 6, 7, 8, 9] # Positive Indexing print(x[0]) print(x[4]) print(x[8]) print('=======\n') # Negative Indexing print(x[-2]) print(x[-4]) print(x[-8])
TIP: Using the Negative values as the list index, the Python start looking for items from right to left.
Please use Negative numbers as the list index to access list items from right to left. It means access list items in reverse order.
# How to Access List Items x = ['apple', 'Mango', 'banana', 'orange', 'cherry','kiwi'] # List Items using Positive Index print("List Item at Index Position 0 = ", x[0]) print("List Item at Index Position 2 = ", x[2]) print("List Item at Index Position 4 = ", x[4]) print("List Item at Index Position 3 = ", x[3]) print('=======\n') # List Items using Negative Index print("List Item at Index Position -1 = ", x[-1]) print("List Item at Index Position -3 = ", x[-3]) print("List Item at Index Position -5 = ", x[-5]) print("List Item at Index Position -6 = ", x[-6])
Alter Python List Items
Since Lists are mutable, apart from accessing items, use this index positions to alter or replace the list items.
Iterate Python List items
A For Loop is the most common way to traverse the list items. The following code helps to iterate the list and print the items inside the list.
Fruits = ['Apple', 'Orange', 'Grape', 'Banana'] for Fruit in Fruits: print(Fruit)
The above-specified code works accurately to print items inside the list. However, to alter the individual list item, we need the index position. To resolve this, we have to use the Python range function along with for loop.
# Altering List using range x = [1, 2, 3, 4, 5, 6, 7, 8, 9] for Number in range(len(x)): x[Number] = x[Number] * 10 print(x)
The above list code multiplies each item with 10. If we want to perform the calculation based on condition, then use Python If Statement inside the for loop.
In this example, we declared a String list.
- The first for loop is to iterate and print the list items.
- The second for loop, along with the range, to iterate each list item using the position of an index.
Let us see another list example.
# Iterate List Items Fruits = ['apple', 'Mango', 'banana', 'orange', 'cherry','kiwi'] # Iterate List Items for fruit in Fruits: print(fruit) # Iterate List Items using Index for i in range(len(Fruits)): print("List Item at Index Position", i, " = ", Fruits[i])
Insert items into List
The following are the list of available options to insert new items into the existing list in Python
- Append(x): This method adds item x at the end of the list.
- Insert(i, x): it inserts the specified list item x at index position i.
- Extend(New_List): This method adds all the list items in New_List at the end of the list.
Fruits = ['Apple', 'Orange', 'Grape', 'Banana'] # Adding items using Python append Fruits.append('Blackberry') print(Fruits) # inserting items using Python insert Fruits.insert(2, 'Kiwi') print(Fruits) # Extending List using Python extend Fruit_new = ['berry','Cherry'] Fruits.extend(Fruit_new) print(Fruits)
Python List Slicing
In python Slice, the first integer value is the index position where the slicing start and the second integer value is the index position where the slicing end.
TIP: List Slicing in Python go untill the second integer value but not include the value at this end index position. For instance, if we specify a list[1:4], then list slicing start at index position one and end at 3 (not 4).
# List slicing x = [1, 2, 3, 4, 5, 6, 7, 8, 9] # Slicing List using two indexes a = x[2:6] print("Both Indexes = ", a) # Slicing List using First indexes b = x[:6] print("No First Index = ", b) # Slicing List using Second indexes c = x[2:] print("No Second Index = ", c) # Slicing List without using two indexes d = x[:] print("No Indexes = ", d)
Use Negative numbers as the index values to slice the list items.
# List slicing x = [1, 2, 3, 4, 5, 6, 7, 8, 9] # Slicing List using Negative indexes e = x[-3:] print("Negative First Index = ", e) # Slicing List using Negative indexes f = x[:-2] print("Negative Second Index = ", f) # Slicing List using Negative indexes g = x[-7:-2] print("Negative First and Second Index = ", g) # Assigning new values to a List x[1:3] = ['t','g'] print("After altering = ", x)
From the above List slicing
- Omit the first index means the Python List Slicing start from the beginning.
- Omit the second index, List slicing start from the first index and continue to the last.
- Use the Negative values to Slice the list items from right to left.
Remove Python List items
There are several ways to delete items from a Lists:
List remove method
If we know the List item or the value inside the List, then use the python remove method to remove the list item.
# Removing Grape Item from Fruit List Fruit1 = ['Apple', 'Orange', 'Grape', 'Banana'] Fruit1.remove('Grape') print(Fruit1) print('========') # Removing Orange Item from Fruits List Fruit2 = ['Apple', 'Orange', 'Grape', 'Banana', 'Orange'] Fruit2.remove('Orange') print(Fruit2) print('========') # Removing Non Existing Grape Item from Fruits1 List Fruit3 = ['Apple', 'Orange', 'Banana'] Fruit3.remove('Grape') print(Fruit3)
List analysis
- Within the first list statement, we are removing the Grape item from the Fruit1 and displaying the remaining list.
- In the second list statement, removed the Orange item from the Fruit2. If you observe closely, we have two Orange items in this list, but the remove method removed only one item. It is because the remove method only deletes the first instance of the list item and ignores the remaining.
- Within the Third list, we removed the nonexisting item. That is why it is throwing an error saying x is not in the list.
Python List del statement
The Delete function removes the list value at a specified index. After deleting, remaining values moved up to fill the index gap.
If we know the Index value or want to delete a range of items from the given list, then use del statement to remove the list item.
# List Delete example Fruits = ['Apple', 'Orange', 'Grape', 'Banana'] del Fruits[1] print(Fruits) print('========') del Fruits[1] print(Fruits) print('========') del Fruits[1] print(Fruits) print('========') del Fruits[1] print(Fruits)
From the above list image,
- Within the First list, we are deleting an item at index position 1, which is Orange. After deleting the Orange, the index position of Grape automatically become one and Banana as 2.
- In the second list, we deleted an item at index position 1, which is Grape.
- Within the Fourth list, we removed the non-existing list item. That is why it throws an error saying index out of range.
Removing Python List items using pop method
The list pop method removes the list items at the specified index and displays the removed element. After removing, remaining list values move up to fill the index gap.
If we know the Index value and want to see the deleted value, we can use python pop to remove the list item.
# List Pop Method example Fruits = ['Apple', 'Orange', 'Grape', 'Banana'] Fruit = Fruits.pop(1) print(Fruits) print('Item extracted by Python Pop = ', Fruit) print('========') Fruit = Fruits.pop(1) print(Fruits) print('Item extracted by Python Pop = ', Fruit) print('========') Fruit = Fruits.pop(1) print(Fruits) print('Item extracted by Python Pop = ', Fruit) print('========')
Python List Methods
The following are the list of methods that are available to perform operations on python list:
Python list copy
List Copy method shallow copy the list items into a completely new list.
# Python List copy Fruits = ['Apple', 'Orange', 'Banana', 'Kiwi', 'Grape', 'Blackberry'] numbers = [9, 4, -5, 0, 22, -1, 2, 14] print("Original List : ", Fruits) print("Original number List : ", numbers) #Copying the List using Python Copy() Method New_Fruits = Fruits.copy() print("\nNew List : ", New_Fruits) new_numbers = numbers.copy() print("New Number List : ", new_numbers)
Python list clear
List clear method clears all the existing list items. After executing this clear method, it returns an empty list.
# Python List clear Fruits = ['Apple', 'Orange', 'Banana', 'Kiwi', 'Grape', 'Blackberry'] numbers = [9, 4, -5, 0, 22, -1, 2, 14] print("Original List : ", Fruits) print("Original number List : ", numbers) #Clear the List using Python Clear() Method New_Fruits = Fruits.clear() print("\nNew List : ", New_Fruits) new_numbers = numbers.clear() print("New Number List : ", new_numbers)
Python list sort
List sort method sorts the list items in the Ascending order.
# Python List sort Fruits = ['Apple', 'Orange', 'Banana', 'Kiwi', 'Grape', 'Blackberry'] numbers = [9, 4, -5, 0, 22, -1, 2, 14] print("Original List : ", Fruits) print("Original number List : ", numbers) #Sort the List using Python sort() Method Fruits.sort() print("\nSorted List : ", Fruits) numbers.sort() print("New Sorted Number List : ", numbers)
Python list reverse
The list reverse method reverses the items in a list.
# Python List reverse Fruits = ['Apple', 'Orange', 'Banana', 'Kiwi', 'Grape', 'Blackberry'] numbers = [9, 4, -5, 0, 22, -1, 2, 14] print("Original List : ", Fruits) print("Original number List : ", numbers) #Reverse the List using Python reverse() Method Fruits.reverse() print("\nReverse List : ", Fruits) numbers.reverse() print("New Reverse Number List : ", numbers)
list index
Python List index function returns the index position of a user-specified value in a list.
# Python List index Fruits = ['Apple', 'Orange', 'Banana', 'Kiwi', 'Grape', 'Blackberry'] numbers = [9, 4, -5, 0, 22, -1, 2, 14] print("Original List : ", Fruits) print("Original number List : ", numbers) #Index of List items using Python index() Method print('The Index position of Kiwi = ', Fruits.index('Kiwi')) print('The Index position of Orange = ', Fruits.index('Orange')) print('The Index position of Grape = ', Fruits.index('Grape')) print('The Index position of 0 = ', numbers.index(0)) print('The Index position of 2 = ', numbers.index(2)) print('The Index position of -1 = ', numbers.index(-1))
Python list count
The List count function counts the total number of times a specified value repeated inside the list.
# Python List count Fruits = ['Apple', 'Orange', 'Banana', 'Kiwi', 'Apple', 'Kiwi'] numbers = [9, 4, -5, 0, 9, -1, 4, 9] print("Original List : ", Fruits) #Count of List items using Python count() Method print('Number of Times Kiwi is repeated = ', Fruits.count('Kiwi')) print('Number of Times Apple is repeated = ', Fruits.count('Apple')) print('Number of Times Banana is repeated ', Fruits.count('Banana')) print("\nOriginal number List : ", numbers) print('Number of Times 9 is repeated = ', numbers.count(9)) print('Number of Times 4 is repeated = ', numbers.count(4)) print('Number of Times 0 is repeated = ', numbers.count(0))
In this Python Lists program, we are applying all the list methods. It might help to understand all the list functions and save the image for further reference.
Fruits = ['Apple', 'Orange', 'Banana', 'Kiwi', 'Grape', 'Blackberry'] x = [9, 4, -5, 0, 22, -1, 2, 14] #Copying the List using Python Copy() Method New_Fruits = Fruits.copy() print(New_Fruits) #Removing all the List items using Python Clear() Method New_Fruits.clear() print(New_Fruits) # Sorting the List using Python Sort() Method Fruits.sort() x.sort() print(Fruits) print(x) # Reverse the List using Python reverse() Method Fruits.reverse() x.reverse() print(Fruits) print(x) # Index position of an item in the List using Python index() Method print('The Index position of Banana = ', Fruits.index('Banana')) print('The Index position of -1 = ', x.index(-1)) # Counting items in the List using Python count() Method y = [9, 4, 1, 4, 9, -1, 2, 4] print('Number of Times 4 is repeated = ', y.count(4)) print('Number of Times 9 is repeated = ', y.count(9))
List sum
The List sum function in Python is to find the sum of all items available in a given lists
# Python List sum int_list = [5, 10, 15, 20, 25] print("List Items : ", int_list) # sum of list elements total = sum(int_list) print("\nThe sum of total items in this list = ", total)
List min and max function
The List min function finds the minimum value.
# Python List min int_list = [50, 10, 150, 20, 205, 500, 7, 25, 175] print("List Items : ", int_list) # Minimum list element minimum = min(int_list) print("\nThe Minimum item in this list = ", minimum)
OUTPUT
The List max function finds the maximum value.
# Python List max int_list = [50, 10, 150, 20, 205, 500, 7, 25, 175] print("List Items : ", int_list) # Maximum list element maximum = max(int_list) print("\nThe Maximum item in this list = ", maximum)
Python List Arithmetic Operations Example
In this example, we show how to use Arithmetic Operators on Python Lists to perform arithmetic operations.
# Python List count x = [10, 20, 30, 40] y = [15, 25, 35, 45] # using + Operator total = x + y print("\nAddition : ", total) # using * Operator multi = x * 2 print("Multiplication : ", multi) multi2 = y * 3 print("Multiplication of Y : ", multi2)
From the above List screenshot, see that
- + operator is concatenating the Lists.
- * operator is repeating the list for a given number of times. Here it is three times.