Python Datatype - Part 2 (Lists)
Abdulmutalib Idris
Head of IT and Media / Full Stack Developer @ Agro Preciso LTD
Python Lists
There are datatype use to store multiple items in single variable. Python have 4 built-in datatype that stores collections of data, they are Tuples, List, Set and Dictionary.
Lists are created using square brackets
mylist = ["Red", "Orange", "Green", "Black"]
print(mylist)
List items are ordered, changeable, and allow duplicate values.
List items are indexed, the first item has index [0], the second item has index [1] etc.
List items can be of any data type
list1 = ["apple", "banana", "cherry"]
list2 = [1, 5, 7, 9, 3]
list3 = [True, False, False]
Ordered: When we say that lists are ordered, it means that the items have a defined order. If you add new items to a list, the new items will be placed at the end of the list.
Changeable: The list is changeable, meaning that we can change, add, and remove items in a list after it has been created.
Allow Duplicates: Since lists are indexed, lists can have items with the same value
mylist = ["Red", "Orange", "Green", "Black", "Red", "Orange",]
print(mylist)
List len()
len() method is use to determine the number of items in a list
mylist = ["Red", "Orange", "Green", "Black"]
print(len(mylist))
A list can contain different data types
list1 = ["abc", 34, True, 40, "male"]
Access List Items
To access the list items, you will need to use the index number to reference them.
Note: The first item has index 0.
mylist = ["Red", "Orange", "Green", "Black"]
print(mylist[1])
Negative Indexing
Negative indexing means starting the index check from the end. -1 refers to the last item, -2 refers to the second last item etc.
mylist = ["Red", "Orange", "Green", "Black"]
print(mylist[-1])
Range of Indexes
You can specify a range of indexes by specifying where to start and where to end the range.
thislist = ["apple", "banana", "cherry", "orange", "kiwi", "melon", "mango"]
print(thislist[2:5])
Note: The search will start at index 2 (included) and end at index 5 (not included).
To start at the first item leave out the start value:
thislist = ["apple", "banana", "cherry", "orange", "kiwi", "melon", "mango"]
print(thislist[:5])
To go to the end item leave out the end value
thislist = ["apple", "banana", "cherry", "orange", "kiwi", "melon", "mango"]
print(thislist[4:])
Range of Negative Indexes
Negative index is use to start the search from the end of the list
mylist = ["Red", "Orange", "Green", "Black", "Blue", "Yellow", "Brown", "White"]
print(mylist[-4:-1])
Check if Item Exists
To determine if a specified item is present in a list use the "in" keyword:
mylist = ["Red", "Orange", "Green", "Black", "Blue", "Yellow", "Brown", "White"]
if "Blue" in mylist:
print("Yes, 'Blue' is in the color list")
else:
print("Yes, 'Blue' is not in the color list")
Change List Items
To change the value of a list item, reference the index number
mylist = ["Red", "Orange", "Green"]
print(mylist)
mylist[1] = "Blue"
print(mylist)
Change a Range of Item Values
To change value of item in a range, define a new list of the value and reference to the range of index
mylist = ["Red", "Orange", "Green", "Black", "Blue", "Yellow", "Brown", "White"]
print(mylist)
mylist[2:5] = ["LightGreen", "Ash", "LightBlue"]
print(mylist)
Add List Items
append() method is use to add new item to the end of the list
mylist = ["Red", "Orange", "Green"]
print(mylist)
mylist.append("Blue")
print(mylist)
Insert Items
insert() method is use to add new item at a specified index
领英推荐
mylist = ["Red", "Orange", "Green"]
print(mylist)
mylist.insert(0, "Blue")
print(mylist)
Extend List
To add items of a list to another list, the extend() method is used
mylist = ["Red", "Orange", "Green"]
mylist2 = ["Black", "Brown", "Blue"]
print(mylist)
mylist.extend(mylist2)
print(mylist)
Extend method can also be use to add other datatype that stores collections of data, like Tuples, Set and Dictionary to a List.
mylist = ["Red", "Orange", "Green"]
mytuple = ("Black", "Brown", "Blue")
print(mylist)
mylist.extend(mytuple)
print(mylist)
Remove Specific Item
remove() method can be used to remove specific item from the list
mylist = ["Red", "Orange", "Green"]
print(mylist)
mylist.remove("Orange")
print(mylist)
Note: If there are more than one item with the specified value, the remove() method removes the first occurrence
Remove Specific Index
To remove item at a specific index, the pop() method is used
mylist = ["Red", "Orange", "Green"]
print(mylist)
mylist.pop(0)
print(mylist)
The del keyword can also remove item at specific index from a list
mylist = ["Red", "Orange", "Green"]
print(mylist)
del mylist[2]
print(mylist)
Clear the List
To clear all items in a list the clear() method can be applied
mylist = ["Red", "Orange", "Green"]
print(mylist)
mylist.clear()
print(mylist)
Loop Lists
You can loop through a list to access the items or perform actions on/using the items. There are various option available to do that:
- for loop:
mylist = ["Red", "Orange", "Green", "Blue"]
for x in mylist:
print(x)
- Loop Through the Index Numbers: Use the range() and len() functions to create a suitable iterable.
mylist = ["Red", "Orange", "Green", "Blue"]
for i in range(len(mylist)):
print(mylist[i])
- Using a While Loop: Use the len() function to determine the length of the list
mylist = ["Red", "Orange", "Green", "Blue"]
i = 0
while i < len(mylist):
print(mylist[i])
i = i + 1
- Looping Using List Comprehension:
mylist = ["Red", "Orange", "Green", "Blue"]
[print(x) for x in mylist]
List Comprehension
Syntax:
newlist = [expression for item in iterable if condition == True]
To create a new list based on application of some condition to an existing list, comprehension is the easiest way. Without comprehension you will have to write a loop statement with conditional test like below:
mylist = ["Red", "Orange", "Green", "Blue"]
newlist = []
for x in mylist:
if "r" in x:
newlist.append(x)
print(newlist)
With list comprehension you can do all that with only one line of code:
mylist = ["Red", "Orange", "Green", "Blue"]
newlist = [x for x in mylist if "r" in x]
print(newlist)
Sort Lists
Sort List Alphanumerically: sort() method is use which sort in ascending order by default
mylist = ["Red", "Orange", "Green", "Blue"]
mylist.sort()
print(mylist)
Sort Descending
mylist = ["Red", "Orange", "Green", "Blue"]
mylist.sort(reverse = True)
print(mylist)
Case Insensitive Sort
By default the sort() method is case sensitive, resulting in all capital letters being sorted before lower case letters:
thislist = ["banana", "Orange", "Kiwi", "cherry"]
thislist.sort()
print(thislist)
Perform a case-insensitive sort of the list by using str.lower as a key function
thislist = ["banana", "Orange", "Kiwi", "cherry"]
thislist.sort(key = str.lower)
print(thislist)
Reverse Order
reverse() is use to reverse the order of a list
thislist = ["banana", "Orange", "Kiwi", "cherry"]
thislist.reverse()
print(thislist)
????? ??????? ??????? ??????? ?? ????? ? ??????? ???? ??? ??????? ??????.
1 年Thank you for your efforts sir. I have issue with the for loop during the sorting of the List, values for x and i are not assigned, and the program prints. Please how does it work?