A Simple Tear Down On List And Arrays
Want to access an array of data without storing them in individual
variables and wasting your memory? This is where the data type list
comes in,
In this article, I'll help you to use lists in python effectively and give you the difference between a List & an Array
What Is A List?
A List is one of 4 built-in data types created with a [square bracket]. With this data type’s help, you can store an array of items in a List.
The items in the list are ordered, allow duplicate values, and are changeable.
These items are indexed as shown in the image below.
Whenever we add a new item to the list the item will be placed at the
end of the list without changing the order of the items inside the
list.
Accessing The Items In A List
The items in the list can be accessed by using the index numbers.
Example Program
cars = ["Audi", "Toyota", "Suzuki"]
print(cars[0])
Output
Audi
Negative Indexing
The negative indexing is used to access the items on the lists starting from the end, as shown in the image above.
Example Program
cars = ["Audi", "Toyota", "Suzuki"]
print(cars[-1])
Output
Suzuki
Access The Items In The List Within A Range Values
You can access the items in the list within the range of the specified start and finish value.
Example Program
cars = ["Audi", "Toyota", "Suzuki", "Kia"]
print(cars[-3:-1])
Output
[‘Toyota’, ‘Suzuki’]
Checking If An Item Exists In A List
To determine whether an item is inside a list or not we use the IN keyword.
Example Program
cars = ["Audi", "Toyota", "Suzuki", "Kia"]
if "Audi" in cars:
print("Audi is in the list of cars")
Output
Audi is in the list of cars
Changing The Items In A List
You can change the value of a specific item by referring to the index number of the item in the list.
Example Program
cars = ["Audi", "Toyota", "Suzuki", "Kia"]
cars[0] = "Jaguar"
print(cars)
Output
[‘Jaguar’, ‘Toyota’, ‘Suzuki’, ‘Kia’]
Changing A Range of Item Values
If you want to change a range of item values, you can define a new list by mentioning the range of the items by their index and number.
Example Program
cars = ["Audi", "Toyota", "Suzuki", "Kia"]
cars[0:2] = ["Jaguar", "Nexa"]
print(cars)
Output
['Jaguar', 'Nexa', 'Suzuki', 'Kia']
Insert A New Item Into A List Using The inset() Function
You can use the insert() function to insert a new item without replacing any other item in the list.
Example Program
cars = ["Audi", "Toyota", "Suzuki"]
cars.insert(2, "Kia")
print(cars)
Output
['Audi', 'Toyota', 'Kia', 'Suzuki']
Adding Items to a list Using The Append Function
You can use the append() method to add an item at the end of the list.
Example Program
cars = ["Audi", "Toyota", "Suzuki"]
cars.append("Kia")
print(cars)
Output
['Audi', 'Toyota', 'Suzuki', 'Kia']
Extending The List Using The extend() Method
By using the extend() method you can append the elements from one list to the other.
Example Program
cars = ["Audi", "Toyota", "Suzuki", "Kia"]
car = ["BMW", "Tata"]
cars.extend(car)
print(cars)
Output
['Audi', 'Toyota', 'Suzuki', 'Kia', 'BMW', 'Tata']
Adding Iterable To A List
You can also append other iterables like sets, tuples, dictionaries, and lists into a list containing other elements using the extend() method.
Example Program With A Tuple
cars = ["Audi", "Toyota", "Suzuki", "Kia"]
car = ("BMW", "Tata")
cars.extend(car)
print(cars)
Output
['Audi', 'Toyota', 'Suzuki', 'Kia', 'BMW', 'Tata']
Example Program With A Dictionary
cars = ["Audi", "Toyota", "Suzuki", "Kia"]
car = {"key1":"BMW", "key2":"Tata"}
cars.extend(car)
print(cars)
Output
['Audi', 'Toyota', 'Suzuki', 'Kia', 'key1', 'key2']
Remove List Items
You can remove an item from a kist by using the methods remove(), pop() and the keyword del.
Removing A Specified Item From A List
You can remove an element from a list by using the remove() method
Example Program
cars = ["Audi", "Toyota", "Suzuki", "Kia"]
cars.remove(“Kia”)
print(cars)
Output
['Audi', 'Toyota', 'Suzuki']
Removing A Specified Index From A List
You can remove an element from a list by specifying the index number of the item in the list to the method pop().
Example Program
cars = ["Audi", "Toyota", "Suzuki", "Kia"]
cars.pop(3)
print(cars)
Output
['Audi', 'Toyota', 'Suzuki']
Example Program Using The del Keyword
cars = ["Audi", "Toyota", "Suzuki", "Kia"]
del.cars[3]
print(cars)
Output
['Audi', 'Toyota', 'Suzuki']
Delete An Entire List
You can also use the keyword del to delete an entire list without a trace.
Example Program Using The del Keyword
cars = ["Audi", "Toyota", "Suzuki", "Kia"]
del cars
print(cars)
Output
NameError: name 'cars' is not defined
Clear An Entier List
You can use the keyword clear() to clear the entire list which will give you an empty list as an output.
Example Program
cars = ["Audi", "Toyota", "Suzuki", "Kia"]
cars.clear()
print(cars)
Output
[ ]
Looping Through Lists
You can loop through a list by using for & while Loops as shown in the below examples.
Example for looping through a list using a For Loop
cars = ["Audi", "Toyota", "Suzuki", "Kia"]
for i in cars:
print(i)
Output
Audi
Toyota
Suzuki
Kia
Example for looping through the index number of a list using a For Loop
cars = ["Audi", "Toyota", "Suzuki", "Kia"]
for i in range(len(cars)):
print(cars[i])
Output
Audi
Toyota
Suzuki
Kia
Example for looping through a list using a While Loop
cars = ["Audi", "Toyota", "Suzuki", "Kia"]
i = 0
while i < len(cars):
print(cars[i])
i = i + 1
Output
Audi
Toyota
Suzuki
Kia
List Comprehension
List Comprehension offers shorter syntax where you can create a new list based on the values of an existing list in a single line of code as shown as follows.
Example For List Comprehension
counting = [i for i in range(5)]
print(counting)
Output
[0, 1, 2, 3, 4]
A Complex Example For List Comprehension
cars = ["Audi", "Toyota", "Suzuki", "Kia"]
updated_cars = [i if i!="Audi" else "Tata" for i in cars]
print(updated_cars)
Output
['Tata', 'Toyota', 'Suzuki', 'Kia']
Sorting Lists
Using the sort() method you can sort an array of lists.
Example For Sorting A List Alphanumerically
cars = ["audi", "Toyota", "Suzuki", "Kia"]
cars.sort()
print(cars)
Output
['Kia', 'Suzuki', 'Toyota', 'audi']
Example For Sorting A List Numerically
num = [9, 2, 3, 4, 5, 1, 7]
num.sort()
print(num)
Output
[1, 2, 3, 4, 5, 7, 9]
Example For Sorting A List Items In Descending Order
num = [9, 2, 3, 4, 5, 1, 7]
num.sort(reverse = True)
print(num)
Output
[9, 7, 5, 4, 3, 2, 1]
Example For Reversing The Items In A List
num = [9, 2, 3, 4, 5, 1, 7]
num.reverse()
print(num)
Output
[7, 1, 5, 4, 3, 2, 9]
Copy Lists
You might be thinking num_1 = num will do the job but it doesn’t in this case whatever change happened to num_1 will affect the original list named num.
To avoid the problem mentioned above you can copy a list by using the methods copy() & list() as shown in the example below.
Example For Using The copy() Method
num = [9, 2, 3, 4, 5, 1, 7]
num_1 = num.copy()
print(num_1)
Output
[9, 2, 3, 4, 5, 1, 7]
Example For Using The list() Method
num = [9, 2, 3, 4, 5, 1, 7]
num_1 = list(num)
print(num_1)
Output
[9, 2, 3, 4, 5, 1, 7]
Joining Lists
There are several ways to join two or more lists, The examples are mentioned below as follows.
Example For Concatenating Two Lists
list_1 = [“cat”, “dog”, “ball”]
list_2 = [“1”, “2”, “3”]
list_3 = list_1 + list_2
print(list_3)
Output
['cat', 'dog', 'ball', '1', '2', '3']
Example For Appending Two Lists
list_1 = [“cat”, “dog”, “ball”]
list_2 = [“1”, “2”, “3”]
for x in list_1:
list_2.append(x)
print(list_2)
Output
['1', '2', '3', 'cat', 'dog', 'ball']
Example For Combining Two List Using The extend() Method
list_1 = [“cat”, “dog”, “ball”]
list_2 = [“1”, “2”, “3”]
list_1.extend(list_2)
print(list_1)
Output
['cat', 'dog', 'ball', '1', '2', '3']
Methods Used In Lists
Methods | Description |
---|---|
append() | Adds an element at the end of the list |
copy() | Returns a copy of the list |
clear() | Removes all the elements from the list |
extend() | Add the elements of a list (or any iterable), to the end of the current list |
count() | Returns the number of elements with the specified value |
sort() | sorts the list |
index() | Returns the index of the first element with the specified value |
insert() | Adds an element at the specified position |
remove() | Removes the first item with the specified value |
pop() | Removes the element at the specified position |
reverse() | Reverses the order of the list |
Difference Between List & Array In Python
List | Array |
---|---|
Example: [1, 2, “Ball”, 4, “Dog”] | Example: [4, 5, 6, 7, 3, 2] |
List is used to collect items that consist of elements of multiple data types. | An array is also a key component that collects several items of a similar data type. |
List cannot manage arithmetic operations. | An Array can manage arithmetic operations. |
List consists of elements that belong to the different data types. | An array consists of elements that belong to the same data type. |
The list allows easy modification of data. | The array does not allow easy modification of data. |
A list consumes a larger memory. | An array consumes less memory than a list. |
In a list, the complete list can be accessed without any specific looping. | In an array, a loop is mandatory to access the components of the array. |
A list favours a shorter sequence of data. | An array favours a longer sequence of data. |
A list contains heterogeneous elements. | Elements stored in an array are homogeneous |
Reference Books
Here are the books I’ve used as references for writing this article, please feel free to read them If you don’t want your knowledge to be limited to this article alone.
FAQ
Which is better array or list ?
An array is faster than a list because the elements stored in an array have the same data type(Homogeneous)
How do you create a list in Python?
In python a list can be created by placing the elements inside square brackets [ ], separated by commas.
A list can accommodate any number of items and like integer, float, string, etc..
A list can also have another list as an item.
What is the use of a list ?
You can store multiple items with different data types in a single variable.
How lists are stored in Python ?
The data in the list is stored in a contiguous block of memory using python’s built-in module named ‘array’ which is similar to arrays in C or C++.
Post a Comment