The Noobs of Python: Ep.2.1 - List : Slice, Loops and more [Updated]

Picking up from 'The Noobs of Python Ep.2 List' we start to delve deeper into List with Slice, Loops & more.

This thread has been updated to reflect a more concise direction with this and future additions to the Ep.2 series

Q: What are Slices?
A: Slicing is used to fetch multiple items from a sequence. Slices are written using the same notation as an index, but this time with two or three integers separated by colons. The first value is the inclusive starting point and the second number is the exclusive end point of the slice. ex:

sith = ['Lord', 'Emperor', 'Darth', 'Count']

sith[1:3] will return  ['Emperor', 'Darth']

Note : The first thing you will notice is that indexing is zero-based, that means you start counting at 0.
So sith[0:2] means that the slice will start from index 0 and stop just before index 2,
(i.e., fetch items at positions 0 and 1). Here are some examples below:

|------|----------|---------|-------|
['Lord', 'Emperor', 'Darth', 'Count']
|------|----------|---------|-------|
   0         1         2        3

Doing sith[0:1] will return'Lord' since it is 0 and ends before 1:

>>> sith[0:1]
['Lord']

The syntax for slice is as follows:

sith[start:end] # items start through end-1
sith[start:]    # items start through the rest of the array
sith[:end]      # items from the beginning through end-1
sith[:]         # a copy of the whole array

There is also the step value, which can be used with any of the above:

sith[start:end:step] # start through not past end, by step

>>> sith[0:3:2]
['Lord', 'Darth']
>>>

Q: Wait a minute? You never mentioned loops before?! How does that work?
A: Technically, a for loop repeats the code block once for each value in a
list or list-like value, so picture this:

for i in range(9):
print(i)
1 2 3 4 5 6 7 8

This is because the return value from range(9) is a list-like value that
Python considers similar to [0, 1, 2, 3, 4, 5, 6, 7, 8] which is why I thought it
would be good to package the explanations. Below we will do some string concatenation and using the list jedi and we'll run a for loop to iterate over indexes of a list. You can do this with your favorite text editor and saving the file as jedi.py or just running it in idle3

jedi = ['Luke', 'Obi Wan', 'Ezra', 'Kanan']

for x in range(len(jedi)):
    print('Index ' + str(x) + ' in Jedi ' + jedi[x])

this returns  :
Index 0 in Jedi Luke
Index 1 in Jedi Obi Wan
Index 2 in Jedi Ezra
Index 3 in Jedi Kanan

PRO TIP: We can also use a for loop to create something interesting with List... Taking a peak into List comprehension. Look at the example below:

>>> A = [None] * 3
>>> for i in range(3):
	A[i] = [None] * 3

>>> A
[[None, None, None], [None, None, None], [None, None, None]]
>>>

This is called a Multidimensional list, this is a form of nesting and some people are familiar with this from other languages like C called arrays. We used the for loop to create an empty List with 3 list within, each with 3 indexes within it. If you have questions, Post them in the comments section!

Below we will populate this empty multidimensioanl list in a short example to get an understanding of the lists within a list:

>>> A[0][1] = str('Spiderman')
>>> A
[[None, 'Spiderman', None], [None, None, None], [None, None, None]]
>>> A[0][0] = str('Peter Parker')
>>> A
[['Peter Parker', 'Spiderman', None], [None, None, None], 
[None, None, None]]
>>> A[0][2] = str('Avengers')
>>> A
[['Peter Parker', 'Spiderman', 'Avengers'], [None, None, None], 
[None, None, None]]
>>>

In that example we populate List [0] and it's indexes [x]. We can keep this going by populating the rest of the list and even use the method .append() to add a list within this list as follows:

A.append(['Reed Richards', 'Mr. Fantastic', 'Fantastic Four'])
>>> A
[['Peter Parker', 'Spiderman', 'Avengers'], [None, None, None], 
[None, None, None], ['Reed Richards', 'Mr. Fantastic', 'Fantastic Four']]
>>>

Post your code and combine what you have learn to see what crazy stuff you come up with ! If you have questions just ask ! Happy Coding Code_Warriors

8 Likes

Ok lets do another Uber Noobs of python breakdown of the above:

Lest start with small lists refresher:

As you have noticed lists can contain many different data types. Above sith list cantains strings

sith = ['Lord', 'Emperor', 'Darth', 'Count']

And this one contains integers:

list1 = [1, 2, 3, 4]

and this one contains other lists:

test1 = [['a', 'b', 'c', 'd', 'e', 'f', 'g'], ['m', 'n'], ['x', 'y', 'z']]

to call your data from list you have to remember that index of the lists starts with 0 in python and lists within lists work the same way.

test1 = [['a', 'b', 'c', 'd', 'e', 'f', 'g'], ['m', 'n'], ['x', 'y', 'z']]
         |[0]  [1]  [2]  [3]  [4]  [5]  [6]|  |[0]  [1]|  |[0]  [1]  [2]|
         |_________________________________|  |________|  |_____________|  

                         [0]                      [1]           [2]

So to call if i want to call 'a' i need to do print(test1[0][0]) otherwise if i just do print[0] the output will be: ['a', 'b', 'c', 'd', 'e', 'f', 'g']

I thing this part is self explanatory:

However there is another way to slice the list. Lest go back to our example sith list:

sith = ['Lord', 'Emperor', 'Darth', 'Count']

We can call for all the values from specific index in the list to its end.

>>> sith = ['Lord', 'Emperor', 'Darth', 'Count']
>>> sith[1:]
['Emperor', 'Darth', 'Count']
>>>

As you can see this will for all the values from second item with index 1 (including that value) to the end of the list. We can do exactly the same thing with calling all the values from the beginning of the list up to (but not including) specified index number:

>>> sith = ['Lord', 'Emperor', 'Darth', 'Count']
>>> sith[:2]
['Lord', 'Emperor']
>>>

Loops

As above i think @Miguel_Sensacion explanation on loops is very good. Now if you have been following along with @Miguel_Sensacion (and you should), check each of his examples and try to modify it you will see that the program he wrote to create list of Sith names is clearly not working and we need to fix it!

Please follow up with coments in the code for the breakdown and explanation.

# Define sith_names variable as an empty list
sith_names = []

# Call while function. While function will run untill a condition is met. In this case while function will run for ever because it will always be true.
while True:

    #Print message with instructions what to imput. len() function gives lenght of list sith_names
        #since we spefified on the begining that this list is empty it starts with lenght 0 then we adding 1 to it to have out index start with 1
        #once the loop progreses it will increase by 1 and finaly the whole expression is beeing casted(changed) to string to be printed inside the message.
        print('Enter the name of sith ' + str(len(sith_names) + 1) + ' (Or enter nothing and press enter to stop.):')

        #Assign name variable to an imput
        name = input()
        #if statement that will break our while loop if input/name variable is empty
        if name == '':
                #Break statement will breake a most inner loop and continue execution on code
                break
        sith_names = sith_names + [name]  # list concatenation

#Print message
print('The dark lord of the sith names are:')

#Another loop, for loop will repeat the print function for the lenght of sith_names list
for i in range(len(sith_names)):

        print(str(i + 1), sith_names[i])

I hope my comments around the code were clear and helped to break it down rather than confused you.
Now take the above examples and make it your own! :D

1 Like

Continuing with the update to this thread here are some methods to help you along the way. If you have questions on the implementation of these methods, please comment below !

>>> A.insert(3, ['Wasp', 'Nadia Pym'])
>>> A
['Avengers', ['Tony Stark', 'Ironman'], ['Steve Rodgers', 'Captain America'], 
['Wasp', 'Nadia Pym'], ['Thor', 'Eric Masterson'], ['Great Lakes Avengers', 
['Mr.Immortal', 'Craig Hollis'], ['Big Bertha', 'Ashley Crawford'], 
['Doorman', 'Demarr Davis'], ['Flatman', 'Matt']]]

Here we used the .insert() to ... you guessed it, insert A.insert(3, ['Wasp', 'Nadia Pym'])
Q: How does this differ from .append()
A: Well with .insert() you need to specify where to insert your object which can come in handy often. so in the example above, the .insert() is as follows :
.insert( index, object) where as append will just append to the end of the list.

Q: So what are other methods useful to list?
A: .remove() is another useful method to utilize in a List, Here is an example:

>>> A
['Avengers', ['Tony Stark', 'Ironman'], ['Steve Rodgers', 'Captain America'], 
['Wasp', 'Nadia Pym'], ['Thor', 'Eric Masterson'], ['Great Lakes Avengers', 
['Mr.Immortal', 'Craig Hollis'], ['Big Bertha', 'Ashley Crawford'], 
['Doorman', 'Demarr Davis'], ['Flatman', 'Matt']]]
>>>
>>>
>>> A.remove(A[4])
>>> A
['Avengers', ['Tony Stark', 'Ironman'], ['Steve Rodgers', 'Captain America'], 
['Wasp', 'Nadia Pym'], ['Great Lakes Avengers', ['Mr.Immortal', 'Craig Hollis'], 
['Big Bertha', 'Ashley Crawford'], ['Doorman', 'Demarr Davis'], ['Flatman', 'Matt']]]
>>>

As you can see in the example above, we used .remove() to remove the 4th object in the list which is ['Thor', 'Eric Masterson'] if you compare the 2. I used the index number which is 4 for it, but you can used the list object as well.

Also akin to .remove() is another method called .pop() which will remove any give item in the List and return it. Here is an example below:

>>> A.pop(2)
['Steve Rodgers', 'Captain America']
>>> A
['Avengers', ['Tony Stark', 'Ironman'], ['Wasp', 'Nadia Pym'], 
['Great Lakes Avengers', ['Mr.Immortal', 'Craig Hollis'], 
['Big Bertha', 'Ashley Crawford'], ['Doorman', 'Demarr Davis'], 
['Flatman', 'Matt']]]
>>>

As you can see, we .pop(2) which was ['Steve Rodgers', 'Captain America'] as shown from idle3. If you do not specify any number to pop, it will default to the last in the List.

And of course we can clear all of our objects in the lList by using .clear() as seen below:

>>> A.clear()
>>> A
[]
>>>

Now your A list is empty for you to try some other devious things to do with List ! Lol

There are several other methods that can be used with List like : .copy() | .reverse() | .sort() | .count() .extend()
If you have any questions just reply in the comments section below !

Code_One_Code_Warriors !!!