Table of contents
- Overview
- Materials
- Declaring a List Data Type
- List Built-in Methods
- An Example of Using a List Command: Append
- How to Replicate the Append Method
- How to use the Extend Method
- How to Replicate the Extend Method
- How to use the Insert Method
- How to Replicate the Insert Method
- How to use the Remove Method
- How to Replicate the Remove Method
- How to use the Pop Method
- How to Replicate the Pop Method
- How to use the Clear Method
- How to Replicate the Clear Method
- How to use the Index Method
- How to Replicate the Index Method
- How to use the Count Method
- How to Replicate the Count Method
- How to use the Sort Method
- How to Replicate the Sort Method
- How to use the Reverse Method
- How to Replicate the Reverse Method
- How to use the Copy Method
- How to Replicate the Copy Method
- Conclusion
- Sources
Overview
This article will explain how to use Python's built-in methods for Lists and also how to create them from scratch. Creating the built-in methods from scratch is beneficial for interviews, as some interviewers would like to see their interviewees code without relying on these techniques.
Materials
Computer
Python
IDE
Declaring a List Data Type
A list is created by declaring a variable that is equal to a pair of brackets that contain variables or numbers within the code.
An Example of a List
''' Variable name on the left side and its equal
to a bracket []. Within the bracket contains
variables, numbers or other data structures in it. '''
make_a_list = [1,2,3]
List Built-in Methods
Every method follows the same convention in Python, a dot or ".", and after the dot is the name of the command and a (). An example of one command is called ".append()". To use a command, enter the variable name of the list and then the convention and specific name of the command. In the parenthesis for each command, different inputs can be added.
An Example of Using a List Command: Append
The .append() method adds an element to the last index in a List
make_a_list = [1,2,3]
# Variable Name Followed by Method Name
make_a_list.append(5)
print(make_a_list)
# Result:
# [1, 2, 3, 5]
How to Replicate the Append Method
make_a_list = [1,2,3]
``` Below shows two ways how to add more variables to a list
without using .append() ```
# First Way
make_a_list = make_a_list + [5]
# or
# Second Way
make_a_list += [5]
print(make_a_list)
# Result:
# [1, 2, 3, 5]
Adding a new element to any list will be placed in the last index of the list.
How to use the Extend Method
The .extend() method combines two lists into one list. By printing the list variable that comes before the extend method, will show the other list variable was added to it.
list_1 = [1,2]
list_2 = [8,9]
list_1.extend(list_2)
print(list_1)
# Result:
# [1,2,8,9]
How to Replicate the Extend Method
list_1 = [1,2]
list_2 = [8,9]
list_1 = list_1 + list_2
# or
list_1 += list_2
print(list_1)
# Result:
# [1,2,8,9]
How to use the Insert Method
The .insert() method adds an element at any index in the list. Within the parenthesis, the first parameter is the index where the element should be added to, and the second parameter is the element and its data type.
list_1 = [1, 2, 3, 4]
list_1.insert(1, "hello")
print(list_1)
# Result
# [1, 'hello', 2, 3, 4]
How to Replicate the Insert Method
The .insert() method can be replicated by slicing a list to different parts and adding it back together with the desired element.
list_1 = list_1[0:1] + ['hello'] + list_1[1:]
print(list_1)
# print(list_1)
# Result:
# [1, 'hello', 2, 3, 4]
Since this example shows the word 'hello' to be added to the first index of the new list_1. First list_1 is sliced up to index 1, then 'hello' is added to the list and the rest of the elements from list_1 is added by using another slice to modify list_1.
How to use the Remove Method
The .remove() method disposes of the first specified element that appears in the lowest positive index.
list_1 = [1, 2, 3, 4, 2]
list_1.remove(2)
# print(list_1)
# Result
# [1, 3, 4, 2]
How to Replicate the Remove Method
The .remove() method can be replicated by slicing the list into different pieces and adding it back together without the specific element.
list_1 = list_1[0:1] + list_1[2:]
print(list_1)
# Result
# [1, 3, 4, 2]
How to use the Pop Method
The .pop() method takes a parameter for the index for which to remove that element from. If no parameter is specified, then the last element from the list is removed.
list_1 = [1, 2, 3, 4, 2]
list_1.pop(3)
print(list_1)
# Result
# [1, 2, 3, 2]
How to Replicate the Pop Method
Just like the remove method, the pop method can be replicated by slicing the list into different pieces and adding it back together without the specific element.
How to use the Clear Method
The .clear() method makes the list variable into an empty list.
list_1 = [1,2,3]
list_1.clear()
# print(list_1)
# Result
# []
How to Replicate the Clear Method
To replicate the .clear() method, a variable can be reassigned to an empty list or a [], which indicates an empty list.
list_1 = [1,2,3]
list_1 = []
# print(list_1)
# Result:
# []
How to use the Index Method
The .index() method accepts a parameter that can be of any data type, and the .index() method returns which index that element can be found at the lowest index.
list_1 = [1, 2, 3, 4, 2]
# print(list_1.index(2))
# Result:
# 1
# In this case, the number 2 is searched for and is found at index 1
How to Replicate the Index Method
To replicate the index method, a for loop can be used to iterate through the list and find, the specific element that is in the list.
# Declare the list
list_1 = [1, 2, 3, 4, 2]
''' Declare a variable that needs to be incremented
to check for the list elements. In this case,
the variable is index. '''
index = 0
''' Make a for loop, until it reaches the last element
of the list. 'in range(0, len(list_1)) makes it
the for loop iterate through the first index to
the last index because of len(list_1) '''
''' Add an if statement to see if the element is
present in the list. Also increment the declared
variable that needs to be increased. '''
for i in range(0, len(list_1)):
if list_1[index] == 2:
print("Match at index " + str(index))
index += 1
The Index Code without Comments
list_1 = [1, 2, 3, 4, 2]
index = 0
for i in range(0, len(list_1)):
if list_1[index] == 2:
print("Match at index " + str(index))
index += 1
How to use the Count Method
The .count() method outputs how many times a certain element is in the list.
list_1 = [1, 2, 9, 4, 9]
# print(list_1.count(9))
# Result:
# 2
How to Replicate the Count Method
The .count() method can be replicated by using a for-loop similarly as shown in the index method. Another variable has to be declared as a counter to keep track of, how many times a specific element has been found in the list.
list_1 = [1, 2, 9, 4, 9]
index = 0
times_element_appeared = 0
for i in range(0, len(list_1)):
if list_1[index] == 9:
print("Match at index " + str(index))
times_element_appeared += 1
index += 1
# print("Times element appeared: " + str(times_element_appeared))
# Result:
# Match at index 2
# Match at index 4
# Times element appeared: 2
How to use the Sort Method
The .sort() method can be used to sort integers or string in ascending or descending order.
# Print in Ascending Order:
words = ["chicken", "beef", "pork", "turkey"]
words.sort()
print(words)
# Result:
# ['beef', 'chicken', 'pork', 'turkey']
# Print in Descending Order
words = ["chicken", "beef", "pork", "turkey"]
words.sort(reverse=True)
print(words)
# Result:
# ['turkey', 'pork', 'chicken', 'beef']
How to Replicate the Sort Method
The .sort() method can be created by using a nested for loop and swapping integers or words in one line.
Sorting integers or floats:
list_one = [1, 9.2, 9, 8, 15, 13.7]
for index_one in range(len(list_one)):
for index_two in range(index_one + 1, len(list_one)):
if list_one[index_one] > list_one[index_two]:
list_one[index_one], list_one[index_two] = list_one[index_two], list_one[index_one]
print(list_one)
Sorting strings:
list_two = ["pork", "turkey", "chicken", "beef"]
for index_one in range(len(list_two)):
for index_two in range(index_one + 1, len(list_two)):
if list_two[index_one] > list_two[index_two]:
list_two[index_one], list_two[index_two] = list_two[index_two], list_two[index_one]
print(list_two)
How to use the Reverse Method
The .reverse() method reverses an entire list.
list_1 = [1, 2, 9, 4, 7]
list_1.reverse()
# print(list_1)
# Result:
# [7, 4, 9, 2, 1]
How to Replicate the Reverse Method
A list can be printed reverse by slicing using [::-1]. The first two parameters do not have to be specified since it automatically will start from the largest index and decrease to the lowest index since the last parameter -1, will decrease to the lowest index.
list_1 = [1, 2, 9, 4, 7]
print(list_1[::-1])
How to use the Copy Method
The .copy() method makes another variable an exact copy of another created list.
list_1 = [1, 2, 9, 4, 7]
list_2 = list_1.copy()
# print(list_1)
# Result:
# [1, 2, 9, 4, 7]
How to Replicate the Copy Method
The copy method can be replicated by assigning a new variable to equal an already created list.
list_1 = [1, 2, 9, 4, 7]
list_2 = list_1
# print(list_2)
# Result:
# [1, 2, 9, 4, 7]
Conclusion
With a list, you can:
Add elements
Extend or combine two lists into one
Insert an element at any index
Remove elements
Pop an element or remove an element from a certain index
Clear the entire list
Find the index where a certain variable or number is
Count how many times the same element appears in a list
Sort a list
Reverse all the elements in a list
Copy a list