1 0
Read Time:7 Minute, 14 Second

Python List

A list contains items separated by commas and enclosed within square brackets ([]). To some extent, lists are similar to arrays in C. One difference between them is that all the items belonging to a list can be of different data type.

The values stored in a list can be accessed using the slice operator ([ ] and [:]) with indexes starting at 0 in the beginning of the list and working their way to end -1.
The plus (+) sign is the list concatenation operator, and the asterisk (*) is the repetition operator.

Example:

x= [ 'abcd', 11, 2.23, 'Ram', 70.2 ]
thislist = [123, 'Ram']

print(x)          # Prints complete list
print(x[0])       # Prints first element of the list
print(x[1:3])    # Prints elements starting from 2nd till 3rd 
print(x[2:])     # Prints elements starting from 3rd element
print(thislist * 2)  # Prints list two times
print(x+ thislist) # Prints concatenated lists

Output:

['abcd', 11, 2.23, 'Ram', 70.2]
abcd
[11, 2.23]
[2.23, 'Ram', 70.2]
[123, 'Ram', 123, 'Ram']
['abcd', 11, 2.23, 'Ram', 70.2, 123, 'Ram']

List Features:

1. Ordered

It means that the items have a defined order, and that order will not change.

2. Changeable

We can change, add, and remove items in a list after it has been created.

3. Allow Duplicates

lists can have items with the same value.

List Methods

MethodDescription
append()Adds an element at the end of the list
clear()Removes all the elements from the list
copy()Returns a copy of the list
count()Returns the number of elements with the specified value
extend()Add the elements of a list (or any iterable), to the end of the current list
index()Returns the index of the first element with the specified value
insert()Adds an element at the specified position
pop()Removes the element at the specified position
remove()Removes the item with the specified value
reverse()Reverses the order of the list
sort()Sorts the list

List Length

Use len() function to get how many items in list.

thislist = ["apple", "banana", "cherry"]
print(len(thislist))
#Output:3

List type

Use type() function to get the type of any python object.

mylist = ["apple", "banana", "cherry"]
print(type(mylist))
#Output:<class 'list'>

The list() Constructor

Using list() constructor to create a new list.

thislist = list(("apple", "banana", "cherry"))

List Operations:

1. Access List Items

List items are indexed and you can access them by referring to the index number:
The first item has index 0.

fruits= ["apple", "banana", "cherry"]
print(fruits[1])

Negative Indexing

Negative indexing means start from the end.
-1 refers to the last item, -2 refers to the second last item etc.

Print the last item of the list:

fruits = ["apple", "banana", "cherry"]
print(fruits[-1])

Range of Indexes

A range of indexes by specifying where to start and where to end the range.
When specifying a range, the return value will be a new list with the specified items.

Example

Return the third, fourth, and fifth item:

fruits = ["apple", "banana", "cherry", "orange", "kiwi", "melon", "mango"]
print(fruits[2:5])

The search will start at index 2 (included) and end at index 5 (not included).

Example

By leaving out the start value, the range will start at the first item:

fruits = ["apple", "banana", "cherry", "orange", "kiwi", "melon", "mango"]
print(fruits[:4])

Example

By leaving out the end value, the range will go on to the end of the list:

fruits = ["apple", "banana", "cherry", "orange", "kiwi", "melon", "mango"]
print(fruits[2:])

Check if Item Exists

fruits = ["apple", "banana", "cherry"]
print("apple" in fruits)
#Output: True

2. Change List Item

Example: Change Item Value

To change the value of a specific item, refer to the index number:

fruits = ["apple", "banana", "cherry"]
fruits[1] = "mango"

Example: Change a Range of Item Values

To change the value of items within a specific range, define a list with the new values, and refer to the range of index numbers where you want to insert the new values:

fruits = ["apple", "banana", "cherry", "orange", "kiwi", "mango"]
fruits[1:3] = ["blackcurrant", "watermelon"]
print(fruits)
#Output : ['apple', 'blackcurrant', 'watermelon', 'orange', 'kiwi', 'mango']

Note: The length of the list will change when the number of items inserted does not match the number of items replaced.

insert() Function

To insert a new list item, without replacing any of the existing values, we can use the insert() method.
The insert() method inserts an item at the specified index:

thislist = ["apple", "banana", "cherry"]
thislist.insert(2, "watermelon")
print(thislist)
#Output: ['apple', 'banana', 'watermelon', 'cherry']

3. Add List Items

Append Items

To add an item to the end of the list, use the append() method:

thislist = ["apple", "banana", "cherry"]
thislist.append("orange")
print(thislist)

Extend List

To append elements from another list to the current list, use the extend() method.

thislist = ["apple", "banana", "cherry"]
tropical = ["mango", "pineapple", "papaya"]
thislist.extend(tropical)
print(thislist)
#Output: ['apple', 'banana', 'cherry', 'mango', 'pineapple', 'papaya']

The elements will be added to the end of the list.

Add Any Iterable

The extend() method does not have to append lists, you can add any iterable object (tuples, sets, dictionaries etc.).
Add elements of a tuple to a list:

thislist = ["apple", "banana", "cherry"]
thistuple = ("kiwi", "orange")
thislist.extend(thistuple)
print(thislist)
#Output : ['apple', 'banana', 'cherry', 'kiwi', 'orange']

4. Remove List Items

Remove Specified Item

The remove() method removes the specified item.

thislist = ["apple", "banana", "cherry"]
thislist.remove("banana")
print(thislist)
#Output : ['apple', 'cherry']

Remove Specified Index

The pop() method removes the specified index.
Remove the second item:

thislist = ["apple", "banana", "cherry"]
thislist.pop(1)
print(thislist)
#Output : ['apple', 'cherry']

If you do not specify the index, the pop() method removes the last item.

thislist = ["apple", "banana", "cherry"]
thislist.pop()
print(thislist)
#Output: ['apple', 'banana']

The del keyword also removes the specified index:

thislist = ["apple", "banana", "cherry"]
del thislist[0]
print(thislist)
#Output : ['banana', 'cherry']

The del keyword can also delete the list completely.

thislist = ["apple", "banana", "cherry"]
del thislist 
print(thislist) #this will cause an error because you have succsesfully deleted "thislist".

5. Loop Lists

Loop Through a List

thislist = ["apple", "banana", "cherry"]
for x in thislist:
  print(x)

Loop Through the Index Numbers

thislist = ["apple", "banana", "cherry"]
for i in range(len(thislist)):
  print(thislist[i])

Using a While Loop

thislist = ["apple", "banana", "cherry"]
i = 0
while i < len(thislist):
  print(thislist[i])
  i = i + 1

Looping Using List Comprehension

thislist = ["apple", "banana", "cherry"]
[print(x) for x in thislist]

6. Sort Lists

Sort List Alphanumerically

List objects have a sort() method that will sort the list alphanumerically, ascending, by default:

Sort the list alphabetically:

thislist = ["orange", "mango", "kiwi", "pineapple", "banana"]
thislist.sort()
print(thislist)

Sort the list numerically:

thislist = [100, 50, 65, 82, 23]
thislist.sort()
print(thislist)

Sort Descending:

# alphabet sorting in descending order
thislist = ["orange", "mango", "kiwi", "pineapple", "banana"]
thislist.sort(reverse = True)
print(thislist)

# number sorting in descending order
thislist = [100, 50, 65, 82, 23]
thislist.sort(reverse = True)
print(thislist)

Case Insensitive Sort

By default the sort() method is case sensitive, resulting in all capital letters being sorted before lower case letters:

Perform a case-insensitive sort of the list:

thislist = ["banana", "Orange", "Kiwi", "cherry"]
thislist.sort(key = str.lower)
print(thislist)

7. Reverse Order

The reverse() method reverses the current sorting order of the elements.

thislist = ["banana", "Orange", "Kiwi", "cherry"]
thislist.reverse()
print(thislist)

8. Copy Lists

You cannot copy a list simply by typing list2 = list1, because: list2 will only be a reference to list1, and changes made in list1 will automatically also be made in list2.

There are ways to make a copy, one way is to use the built-in List method copy().

thislist = ["apple", "banana", "cherry"]
mylist = thislist.copy()
print(mylist)

Another way to make a copy is to use the built-in method list().

thislist = ["apple", "banana", "cherry"]
mylist = list(thislist)
print(mylist)

9. Join Lists

There are several ways to join, or concatenate, two or more lists in Python.

One of the easiest ways are by using the + operator.

list1 = ["a", "b", "c"]
list2 = [1, 2, 3]

list3 = list1 + list2
print(list3)

Another way to join two lists is by appending all the items from list2 into list1, one by one:

list1 = ["a", "b" , "c"]
list2 = [1, 2, 3]

for x in list2:
  list1.append(x)

print(list1)

Or you can use the extend() method, which purpose is to add elements from one list to another list:

list1 = ["a", "b" , "c"]
list2 = [1, 2, 3]

list1.extend(list2)
print(list1)
Happy
Happy
100 %
Sad
Sad
0 %
Excited
Excited
0 %
Sleepy
Sleepy
0 %
Angry
Angry
0 %
Surprise
Surprise
0 %
Verified by MonsterInsights