Python Lists
Python List
Multiple items are saved in a single variable in lists.
Note :- Lists are created using square brackets.
Example :- A simple list program
mylist = ["London", "Paris", "Berlin"]
print(mylist)
Output :-
List Items
List items are requested, modifiable, and permissible for duplication.
The items in the list are indexed, with the first item having index [0]
, the second having index [1]
, and so on.
Ordered
Because once we say that a list is ordered, we indicate that the items are arranged in a specific order that will not change.
The new items will be attached to the end of the list when you add new items to a list.
Note : some processes in the list will change the sequence, but generally : there are no changes in the order of objects.
Changeable
The list is changable, that means that after it is created we can change, add and delete items from the list.
Allow Duplicates
Lists can have the same item value because they are indexed :
Example :- Lists allow duplicate values :
mylist = ["London", "Paris", "Berlin", "Paris"]
print(mylist)
Output :-
List Length
Just use len()
function to determine the number of items on a list :
Example :- The total number of items in the list should be printed :
mylist = ["London", "Paris", "Berlin"]
print(len(mylist))
Output :-
Related Links
Check if Item Exists
Using the in
keyword, you can check to see if a specific item is in a list of items.
Example :- Check to see if the word "London" appears in the list :
mylist = ["London", "Paris", "Berlin"]
if "London" in mylist:
print("Yes, 'London' is in the mylist")
Output :-
List Items - Data Types
A List can have any type of data in it.
Example 1 :- A simple list with string, int and boolean data types :
list1 = ["London", "Paris", "Berlin"]
list2 = [1, 5, 7, 9, 3]
list3 = [True, False, False]
print(list1)
print(list2)
print(list3)
Output :-
[1, 5, 7, 9, 3]
[True, False, False]
Various data types can be found in a single list.
Example 2 :- Strings, numbers, and boolean values are all included in this list :
list1 = [101, "abc", 20000.50, "male"]
print(list1)
Output :-
type()
Python defines lists as objects with the data type 'list' from the perspective of Python :
Example :- What type of data does a list contain ?
mylist = ["apple", "banana", "cherry"]
print(type(mylist))
Output :-
The list() Constructor
The list()
constructors can also be used when a new list is created :
Access List Items
Items in the list are indexed, and you can find them by referring to the index number.
Example :- The second item in the list should be printed :
mylist = ["London", "Paris", "Berlin"]
print(mylist[1])
Note:- The first item has index 0.
Related Links
Negative Indexing
Indexing in the negative direction means starting from the end.
-1
refers to the last item, -2
refers to the second last item etc.
Example :- The last item in the list should be printed :
mylist = ["London", "Paris", "Berlin"]
print(mylist[-1])
Output :-
Range of Indexes
By selecting where to start and where to end the range, you can specify a range of indexes.
In the case of specifying a range, the return value will be a new list with the items supplied.
Example 1 :- The third, fourth, and fifth items should be returned :
mylist = ["apple", "banana", "grapes", "orange", "papaya", "melon", "mango"]
print(mylist[2:5])
#This will return the items from position 2 to 5.
#Remember that the first item is position 0,
#and note that the item in position 5 is NOT included
Output :-
Index 2 (included) is the starting point of the search. Index 5 is the end destination (not included).
Keep in mind that the first item has an index of 0.
The range will extend to the beginnig of the list if the start value is omitted from the syntax :
Example 2 :- "orange" is NOT included in this example, thus it returns the things from the beginning :
mylist = ["apple", "banana", "grapes", "orange", "papaya", "melon", "mango"]
print(mylist[:3])
#This will return the items from index 0 to index 3.
#Remember that index 0 is the first item, and index 3 is the fourth item
#Remember that the item in index 3 is NOT included
Output :-
The range will extend to the end of the list if the end value is omitted from the formula :
Example 3 :- This example retrieves all of the items from "grapes" through the end of the list of items returned :
mylist = ["apple", "banana", "grapes", "orange", "papaya", "melon", "mango"]
print(mylist[2:])
#This will return the items from index 2 to the end.
#Remember that index 0 is the first item, and index 2 is the third
Output :-
Change List Item Value
Modify a specific item's index number to change the value of a certain item's value :
Example :- Change the third item :
mylist = ["London", "Paris", "Berlin"]
mylist[2] = "Tokyo"
print(mylist)
Output :-
Change a Range of Item Values
To modify the value of items inside a certain range, construct a list with the new values and refer to the range of index numbers where you wish to insert the new values :
Example 1 :- modify the values "orange" and "mango" with the values "banana" and "grapes" :
mylist = ["apple", "orange", "mango"]
mylist[1:3] = ["banana", "grapes"]
print(mylist)
Output :-
If you input more items than you replace, the new items will be placed where you stated, and the leftover items will be moved accordingly :
Example 2 :- It is possible to change the second value by replacing two new ones :
mylist = ["London", "Paris", "Berlin"]
mylist[1:2] = ["New York", "Sydny"]
print(mylist)
Output :-
Note :- When the number of things introduced does not equal the number of items replaced, the length of the list will change.
As long as you don't replace more than you add, the new items will be placed where you requested, and the other items will be moved accordingly.
Example 3 :- As a result, the second and third values have been changed to a single value :
mylist = ["London", "Paris", "Berlin"]
mylist[1:3] = ["New York"]
print(mylist)
Output :-
Python - Add List Items
Python has several methods to add new items to a list.
Append Items
Use the append()
method to add an item to the end of the list.
Example :- The append()
method is used to append an item to the list :
mylist = ["London", "Paris", "Berlin"]
mylist.append("Singapore")
print(mylist)
Output :-
Insert Items
The insert()
method can be used to add a new list item without altering any of the existing values.
When you call the method insert()
, it will insert a new item at the given index :
Example :- Insert "New York" as the third item:
mylist = ["London", "Paris", "Berlin"]
mylist.insert(2, "New York")
print(mylist)
Output :-
Note: Like a outcome of the preceding example, the list now contains four items.
Extend List
Use the extend()
method to append elements from another list to the current one.
Example :- Add the elements of mylist2
to mylist
:
mylist = ["London", "Paris", "Berlin"]
mylist2 = ["Singapore", "Malasiya"]
mylist.extend(mylist2)
print(mylist)
Output :-
The elements will be placed at the end of the list.
Add Any Iterable
Any iterable object can be added using the extend()
method, not append lists (tuples, sets, dictionaries etc.).
Example :- Add elements of a tuple to a list :
mylist = ["London", "Paris", "Berlin"]
mytuple = ("Singapore", "Malasiya")
mylist.extend(mytuple)
print(mylist)
Output :-
Remove Specified List Item
The remove()
method is used to remove the given list item object from the list.
Example :- Remove a list item contains "Berlin" object :
mylist = ["London", "Paris", "Berlin"]
mylist.remove("Berlin")
print(mylist)
Output :-
Remove Specified Index
The pop()
method removes the provided index item from the list.
Example 1 :- Remove the third item :
mylist = ["London", "Paris", "Berlin"]
mylist.pop(2)
print(mylist)
Output :-
Note :- The pop()
method removes the last item if you don't give the index.
Example 2 :- Remove the last item :
mylist = ["London", "Paris", "Berlin"]
mylist.pop()
print(mylist)
Output :-
Removes selected index with del
keyword :
Example 3 :- Remove the first item :
mylist = ["London", "Paris", "Berlin"]
del mylist[0]
print(mylist)
Output :-
The del
keyword can also be used to remove all items from the list.
Example 4 :- Delete the entire list :
mylist = ["London", "Paris", "Berlin"]
del mylist
print(mylist)
Note :- This will cause an error because you have succsesfully deleted "mylist".
Clear the List
The clear()
method is used to remove all items from the list, but not list itself.
The list still remains, but it has no content.
Example :-
mylist = ["London", "Paris", "Berlin"]
mylist.clear()
print(mylist)
Output :-
Python - Loop Lists
Loop Through a List
Using a for
loop, you may loop through the list elements.
Example :- Print all items in the list, one by one :
mylist = ["London", "Paris", "Berlin"]
for x in mylist:
print(x)
Output :-
Paris
Berlin
Loop Through the Index Numbers
The index number can also be used to loop through the list entries.
In order to generate a proper iterable, you will need to use the range()
and len()
methods.
Example :- All items can be printed by referring to their corresponding index number :
mylist = ["London", "Paris", "Berlin"]
for i in range(len(mylist)):
print(mylist[i])
Output :-
Paris
Berlin
In the example above, the iterable produced is [0
, 1
, 2
].
Using a While Loop
Using a while
loop, you may loop through the list elements.
To get the length of the list, use the len()
function, then begin at 0 and work your way through the entries by referring to their indexes.
Remember to increment the index by one after each iteration.
Example :- Using a while
loop to iterate through all the index numbers, print all items :
mylist = ["London", "Paris", "Berlin"]
i = 0
while i < len(mylist):
print(mylist[i])
i = i + 1
Output :-
Paris
Berlin
Looping Using List Comprehension
When looping through lists, List Comprehension provides the shortest syntax :
Example 1 :- A shorthand for
a loop that prints out all elements in a list :
mylist = ["London", "Paris", "Berlin"]
[print(x) for x in mylist]
Output :-
Paris
Berlin
When you wish to construct a new list based on the values of an existing list, list comprehension gives a more concise syntax for the task.
Based on a list of names, you want a new list that only contains name with the letter "n"
in their name.
Example 2 :- You will have to build a for
statement with a conditional test inside if you don't have list comprehension :
mylist = ["London", "Paris", "Berlin"]
newlist = [x for x in mylist if "a" in x]
print(newlist)
Output :-
Python - Sort Lists - Ascending or Descending
Python provides sorting in multiple ways. A list can have sorting with any datatypes like string, numbers and booleans.
Sort List Alphanumerically
There is a method on list objects called sort()
that defaults to alphanumerically sort the list in ascending order :
Example 1 :- Sort the list of strings alphabetically :
mylist = ["Ford", "BMW", "Toyoto"]
mylist.sort()
print(mylist)
Output :-
Example 2 :- Sort the list of numbers in ascending order :
mylist = [100, 50, 65, 82, 23]
mylist.sort()
print(mylist)
Output :-
Sort Descending
Use the keyword argument reverse = True
to sort in descending order :
Example 1 :- Sort the list of strings in descending order :
mylist = ["Ford", "BMW", "Toyoto"]
mylist.sort(reverse = True)
print(mylist)
Output :-
Example 2 :- Sort the list of numbers in descending order :
mylist = [100, 50, 65, 82, 23]
mylist.sort(reverse = True)
print(mylist)
Output :-
Customize Sort Function
Using the keyword argument key = function
, you can also create your own function and customise it.
The function will produce a number that is being used to order the data in list (the lowest number first) :
Case In-Sensitive Sort
All capital letters are sorted first in the sort()
method by default because it is case sensitive.
Example 1 :- As a result of using case sensitive sorting, an unexpected result can occur :
mylist = ["banana", "Orange", "Grapes", "apple"]
mylist.sort()
print(mylist)
Output :-
If we want to sort a list, we can take advantage of built-in key functions.
In order to achieve this, use str.lower
as the key function to sort the data.
Example 2 :- Use case-insensitive sorting for the list :
mylist = ["banana", "Orange", "Grapes", "apple"]
mylist.sort(key = str.lower)
print(mylist)
Output :-
Reverse Order
However, what happens if you want to reverse an alphabetically arranged list?
Using the reverse()
method, you can reverse the current sorting order of the elements in the collection.
Example :- Reverse the order of the items in the list :
mylist = ["banana", "Orange", "Kiwi", "cherry"]
mylist.reverse()
print(mylist)
Output :-
Copy a List
You can't just do list2 = list1
to copy a list since list2
is only a record to list1
, and any changes made to list1
will be reflected in list2
.
It is possible to make a copy using the built-in List copy()
function.
The copy()
method is used to return a copy of list.
Example :-
mylist = ["London", "Paris", "Berlin"]
mylist2 = mylist.copy()
print(mylist2)
Output :-
Python - Join Lists
Python provides many ays to join or combine two list.
Join Two Lists
Two or more lists can be joined in Python in a variety of ways, including by concatenation.
Using the +
operator is one of the simplest ways to do this.
Example 1 :- Join two list :
list1 = ["a", "b", "c"]
list2 = [1, 2, 3]
list3 = list1 + list2
print(list3)
Output :-
Two lists can also be joined by adding one item at a time, one by one, from list2 into list1.
Example 2 :- Append list2 items one by one into list1
list1 = ["a", "b" , "c"]
list2 = [1, 2, 3]
for x in list2:
list1.append(x)
print(list1)
Output :-
It's also possible to utilise the extend()
method, which adds elements from one collection to another.
Example 3 :- Use the extend()
method to add list2 at the end of list1 :
list1 = ["a", "b" , "c"]
list2 = [1, 2, 3]
list1.extend(list2)
print(list1)
Output :-