Skip to content

Commit ca2ee4e

Browse files
committed
Added new post
1 parent 1366db6 commit ca2ee4e

1 file changed

Lines changed: 366 additions & 0 deletions

File tree

Lines changed: 366 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,366 @@
1+
---
2+
layout: post
3+
title: Lists Data Types - List Operations, Their Impact on Scripts, and Functions.
4+
description: >-
5+
Lists are a true fascination when it comes to managing and using data within a Python program. We are able to perform several functions and tasks with them which all help with learning List Comprehension. In Day 5, we uncover the functions of lists and how they work.
6+
author: Sheikh Hussain
7+
date: 2025-12-22 22:55:00 +0000
8+
categories: [Python, Courses]
9+
tags: [python, programming, course, 30days, day5, strings]
10+
pin: false
11+
math: false
12+
mermaid: false
13+
image:
14+
path: 012026/python_day5.jpg
15+
alt: Image from Pexels - Python Programming
16+
render_with_liquid: false
17+
media_subpath: /assets/img/posts/
18+
---
19+
20+
This is a well awaited topic that I've been eager to talk about, lists are a data type that create great fascinations for me.
21+
22+
The functions you can perform, the methods you can use, and all the ways you can get it to produce different information is exactly why we learn **Data Structure's and Algorithm's**, DSA[^f2].
23+
24+
By this point of the course however, I only learn about *how to use lists properly* and what they can do so that I might gain some newer insights.
25+
26+
---
27+
28+
## What are lists?
29+
30+
Lists, also known as *collection data types*, are used to store data in an ordered and muatable/changeable format. Think of your everyday list that you would use for shopping, task manager, and etc.
31+
32+
We use lists to store and manage information throughout our program. It's important to also mention that there are different list types that we can use.
33+
34+
Each type has it's own features.
35+
36+
Here is a small table with the different list types I have learnt so far:
37+
38+
| Type | Description | Example |
39+
|---------------|------------------------------------------|-------------------------------------------|
40+
| List | Ordered and modifiable | `items = ["Item1", 5, 12.33, False]` |
41+
| Tuple | Ordered and immutable | `items = ("Item1", 5, 12.33, False)` |
42+
| Set | Unordered, unindexed, and mutable | `items = {"Item1", 5, 12.33, False}` |
43+
| Dictionary | Ordered (Python 3.7+), key-value pairs | `items = {"name": "Item1", "count": 5}` |
44+
45+
46+
> **Note**: When we use the term *ordered* for lists, we mean *preserving* the order in which items were inserted - **not logical ordering**. Lists, Tuples, and Dictionaries **preserve** insertion order. In contrast, *Sets* are unordered, hence if you were to create a set with items in, with each run of the program, you could see the items shift.
47+
{: .prompt-tip}
48+
49+
## Creating lists
50+
51+
There are a few methods we can use to assign/create a list. I want to go into as much detail as I can here, as when I went through this module, I found that knowing these do help when it comes to learning about list comprehension.
52+
53+
Examples:
54+
```python
55+
lst = list() # This creates and empty list
56+
lst = [] # This also creates an empty list
57+
lst = ["Item1", "Item2", 25, 3.14, False, True, {'key':'value'}, ("Tuple"), {"Set"}]
58+
# This creates a list with initial values (different data types including other lists can be stored).
59+
```
60+
61+
By this point, I would recommend playing around with lists which helped me better understand them. It's also useful to start using different built-in functions that we learnt from before, like `len()`.
62+
63+
```python
64+
lst = ["Item1"]
65+
66+
print(len(lst))
67+
# 1
68+
print(lst)
69+
# [Item1]
70+
```
71+
72+
## Adding Items To a List
73+
74+
Now that I've learnt how to create a list, I need to know how to *append* to a list or *modify* it.
75+
76+
There are several methods to doing this and instead of just writing about them, I'll provide examples.
77+
78+
```python
79+
# .append() method
80+
lst = [] # Create an empty list
81+
lst.append("Item1") # You can only use this feature for one element at a time.
82+
# To add multiple items you would have to use this several times.
83+
print(lst) # ["Item1"]
84+
85+
# .insert(index,item) method
86+
lst.insert(0,"Item2") # Insert at index 0 and push the rest to the right (insertion method)
87+
print(lst) # ["Item2", "Item1"]
88+
89+
# .extend() method
90+
lst.extend(["Item3", "Item4", "Item5",])
91+
print(lst) # ["Item2", "Item1", "Item3", "Item4", "Item5"]
92+
93+
# Using Assignment Operators
94+
lst += ["Item6", "Item7"]
95+
print(lst) # ["Item2", "Item1", "Item3", "Item4", "Item5", "Item6", "Item7"]
96+
97+
# List Concatenation
98+
new_lst = lst + ["Item8"]
99+
print(new_lst) # ["Item2", "Item1", "Item3", "Item4", "Item5", "Item6", "Item7", "Item8"]
100+
```
101+
102+
> **List Concatenation** is an operation that produces a *new list* by combinging the items from other lists.
103+
{: .prompt-tip}
104+
105+
We can also use advanced functions like `for loops` to add items into a list using a loop function, with each iteration of the loop an item from a list gets added.
106+
107+
```python
108+
lst = []
109+
110+
for each_item in [1,2,3,4,5]: # The temporary variable 'each_item' represent each item in the list for each pass/iteration/loop
111+
lst.append(each_item)
112+
113+
print(lst) # [1, 2, 3, 4, 5]
114+
```
115+
116+
We can also add multiple items to a list using the `.extend()` function. It's usually used to append a list with another lists contents; Which I'll go over later, but for now...
117+
118+
```python
119+
lst = ["Item1"]
120+
lst.extend(["Item2", "Item3"]) # See how we must still specify another list of items?
121+
print(lst) # ["Item1", "Item2", "Item3"]
122+
```
123+
124+
## Modifying Items In a List
125+
126+
Remember that lists are mutable or changeable and thus, we are able to change an item in a predefined list. To perform this function, you would first call on the list, specify the item in the list or index of the item in the list you want to update, finally we would would use the assignment operator `=` to specify the new value.
127+
128+
```python
129+
lst = ["Cat", "Dog", "Fox", "Bear", "Squirrel", "Snake"]
130+
lst[0] = "Item1"
131+
print(lst) # ["Item1", "Dog", "Fox", "Bear", "Squirrel", "Snake"]
132+
```
133+
134+
All items stored within a list is stored using an index reference number, starting at 0. In addition, an item in a list that is itself a **sequence**, like a string data type, you can further specify an index number to access *its* elements.
135+
136+
```python
137+
lst = ["Cat", "Dog", "Fox", "Bear", "Squirrel", "Snake"]
138+
print(lst[0][0]) # "C"
139+
```
140+
141+
## Removing Items From a List
142+
143+
At any point during our program we might want to remove an
144+
There are more than one method we can use to remove or delete items off a list and instead of diving in deep on all of them, I'll just provide an example of what they all do.
145+
146+
**Delete using `.remove()`**
147+
```python
148+
lst = ["Item1", "Item2", "Item3", "Item4", "Item5"]
149+
lst.remove("Item1") # Specify exact item
150+
print(lst) # ["Item2", "Item3", "Item4", "Item5"]
151+
```
152+
153+
**Delete using `.discard()`**
154+
*This method raises **no error** if the item isn't found.*
155+
```python
156+
lst = ["Item1", "Item2", "Item3", "Item4", "Item5"]
157+
lst.discard("Item1")
158+
print(lst) # ["Item2", "Item3", "Item4", "Item5"]
159+
```
160+
161+
**Delete using `.pop()`**
162+
```python
163+
lst = ["Item1", "Item2", "Item3", "Item4", "Item5"]
164+
lst.pop(1) # Specify index to remove instead
165+
print(lst) # ["Item1", "Item3", "Item4", "Item5"]
166+
167+
#OR
168+
169+
lst.pop() # This will automatically remove the last item from the list
170+
print(lst) # ["Item1", "Item2", "Item3", "Item4"]
171+
```
172+
173+
**Delet using `Del`**
174+
```python
175+
lst = ["Item1", "Item2", "Item3", "Item4", "Item5"]
176+
del lst[0] # deletes first item
177+
print(lst) #["Item2", "Item3", "Item4", "Item5"]
178+
179+
del lst[1:3] # Deleted indeces one to three
180+
print(lst) # ["Item1", "Item5"]
181+
182+
del lst
183+
print(lst) # Produces error, list deleted completely
184+
```
185+
186+
**Deleting using `.clear`**
187+
```python
188+
lst = ["Item1", "Item2", "Item3", "Item4", "Item5"]
189+
lst.clear() # Clears all the contents of a list
190+
print(lst) # []
191+
```
192+
193+
## Joining Lists
194+
```python
195+
lst1 = ["Item1", "Item2"]
196+
lst2 = ["Item3", "Item4"]
197+
lst3 = lst1 + lst2
198+
print(lst3) # ["Item1", "Item2", "Item3", "Item4"]
199+
```
200+
201+
In addition to using the `+` operator to join lists, we can also use the `.extend()` to apply the contents from another list into our list.
202+
203+
```python
204+
lst = ["Item1"]
205+
lst2 = ["Item2"]
206+
lst.extend(lst2)
207+
208+
print(lst) # ["Item1", "Item2"]
209+
```
210+
211+
## Accessing Items In a List
212+
213+
Now that I've learnt the methods to append to a list, we need to know how to access each item in a list.
214+
215+
In my last post, *[String Data Types](https://github.com/Asabeneh/30-Days-Of-Python/blob/master/05_Day_Lists/05_lists.md)*, I discussed the methods of unpacking, slicing, and accessing each character within a string.
216+
217+
We'll now use the same methods on list data types to perform the same actions.
218+
219+
```python
220+
lst = ["Item1", "Item2", "Item3", "Item4", "Item5"]
221+
print(lst[0]) # Item1
222+
print(lst[-1]) # Item5
223+
224+
#Slicing
225+
226+
print(lst[:-1]) # ["Item1", "Item2", "Item3", "Item4"]
227+
print(lst[1:]) # ["Item2", "Item3", "Item4", "Item5"]
228+
print(lst[::-1]) # ["Item5", "Item4", "Item3", "Item2", "Item1"]
229+
print(lst[0:5:2]) # ["Item1", "Item3", "Item5"]
230+
```
231+
232+
Following the same method as before, I've been able to get used to accessing items in a list relatively easily.
233+
234+
## Finding Items In a List
235+
236+
I've learnt about member operators before, and these can also be used on lists to check whether or not an item exists in the list.
237+
238+
```python
239+
lst = ["Cat", "Dog", "Fox", "Bear", "Squirrel", "Snake"]
240+
print("Cat" in lst) # True
241+
print("Lion" in lst) # False
242+
```
243+
244+
> I want to recall a construct that I mentioned before while discussing operators, *constant and runtime sequences*[^f3]. Lists, though sequencial, are mutable and therefore identical lists do not get stored in the same location.
245+
{: .prompt-tip}
246+
247+
## Finding The Index Of An Item
248+
249+
We might want to know what the index number of an item is in a list and for that we have `.index()`.
250+
251+
```python
252+
lst = ["Item1", "Item2"]
253+
print(lst.index("Item1")) # 0
254+
index_ref = lst.index("Item2")
255+
print(index_ref) # 1
256+
```
257+
258+
## Unpacking Lists
259+
260+
This is very similar to the string data type which I found fairly easy to learn.
261+
262+
Something we missed out on the earlier post is using, what AI likes to refer to as *Extended Iterable Unpacking*, to unpack several items into a variable at once.
263+
264+
```python
265+
lst = ["Item1", "Item2", "Item3", "Item4", "Item5"]
266+
267+
a,b,c,*d = lst
268+
269+
print(a) # Item1
270+
print(b) # Item2
271+
print(c) # Item3
272+
print(d) # ["Item4", "Item5"]
273+
```
274+
275+
The `*variable =` assignment operator produces a new list with the *rest* of the items in the list you specify.
276+
277+
> **Hint**: With extended iterable unpacking, you can assign some items to individual variables and use a starred variable (*variable) to collect the remaining items. You can place the starred variable at the start, middle, or end, but you can only have one starred variable.
278+
{: .prompt-tip}
279+
280+
## Copying Lists
281+
282+
Copying a list function can prove to be useful sometimes, we might want to work off a copy of the original data set and so this is available through the `.copy()` function.
283+
284+
First, we would create our original list and provide it with some data - not necessary. Then we would create a new variable and assign a copy of the list on to that variable.
285+
286+
```python
287+
lst = ["Item1", "Item2"]
288+
lst2 = lst.copy()
289+
print(lst2) # ["Item1", "Item2"]
290+
```
291+
292+
## Sorting a List
293+
294+
This is a topic that's discussed in a lot of detail when it comes to learning about Data Structures and Algorithms.
295+
296+
That will be something I write about later in a separate series of its own.
297+
298+
However, for now it's useful for me to know that we can have the contents of a list organised.
299+
300+
```python
301+
302+
lst = ["Item2", "Item5", "Item3", "Item4", "Item1"]
303+
lst.sort() # This does it in ascending order
304+
print(lst) # ["Item1", "Item2", "Item3", "Item4", "Item5"]
305+
lst.sort(reverse = True) # This does it in descending order
306+
print(lst) # ["Item5", "Item4", "Item3", "Item2", "Item1"]
307+
# This does modify the original list
308+
309+
# We also have sorted() which doesn't modify the original list
310+
311+
lst = sorted(lst) # Ascending order
312+
print(lst) # ["Item1", "Item2", "Item3", "Item4", "Item5"]
313+
lst = sorted(lst, reverse = True) # Descending order
314+
print(lst) # ["Item5", "Item4", "Item3", "Item2", "Item1"]
315+
```
316+
317+
While revisiting this topic, the question arose to me about what the difference between `.sort()` and `sorted()` actually is.
318+
319+
The best explanation I could provide on this, even after spending sometime going back and forth with AI to explain the concept, is that `.sort()` **mutates** the original list and `sorted()` creates and **rebinds** a new list when we assign it to the same variable as the old one.
320+
321+
I wanted to make sure that I have this explained as best as I can as it could help later one.
322+
323+
Think of one going in to a list and rearranging the items, the other as temporarily creating a new list and then returning that being arranged or ordered.
324+
325+
ChatGPT did not like it when I would use the phrase '*overwrite* over the existing list variable' and keeps insisting that we say it is being re-bound to the old variable.
326+
327+
The original list is left unchanged and becomes unreferenced.
328+
329+
## Reversing a List
330+
331+
We can also have the contents of our list be reversed without having to sort them using the `.reverse()` function.
332+
333+
```python
334+
lst = ["Item 2","Item 1 ","Item 3"]
335+
lst.reverse()
336+
print(lst) # ["Item 3", "Item 1", "Item 2"]
337+
```
338+
339+
> Note how this just printed it all out in reverse rather than ordering.
340+
{: .prompt-info}
341+
342+
## Counting Items In a List
343+
344+
This is different from `.len()` as instead of counting the total number of items, `.count()` will count the *occurance* of an item you specify in a list.
345+
346+
```python
347+
lst = ["Item 2","Item 1 ","Item 3", "Item 3"]
348+
349+
print(lst.count("Item 3")) # 2
350+
```
351+
352+
## Summary
353+
354+
By the end of writing this post, I've gained a deeper insight into the functions available for the *traditional* list data types and *how* they can be applied.
355+
356+
Though this would be my second pass over the course, I can now better reflect on the importance of each function and how they intereact with list data.
357+
358+
I'll be going over Tuples next, and a lot of the functions will be the same. However, since tuples are **immutable**, some operations would behave differently.
359+
360+
I'm more after repetition and understand of functions, than I am with doing tasks with them. As I think that this will aid my creativity from the understandings I gain.
361+
362+
## Footnotes
363+
364+
[^f1]: [30 Days of Python - Day 5](https://github.com/Asabeneh/30-Days-Of-Python/blob/master/05_Day_Lists/05_lists.md)
365+
[^f2]: [W3 Schools - Data Structures and Algorithms](https://www.w3schools.com/dsa/index.php)
366+
[^f3]: [String Data Types](https://sheikh-h.github.io/Blog/posts/python-day3/#identity-operators)

0 commit comments

Comments
 (0)