The Noobs of Python: Ep.2.0 - List and List of List ! and the List goes on!

The warm welcome to the introductory 'The Noobs of Python' series was well received. Hopefully more people will share their variations on the code examples as we go forward ! This edition is about List and List of List.

Q: So what are Lists in Python?
A: A list is a value that contains multiple values in an ordered sequence. The term list value refers to the list itself not the values inside the list value.

Q: Soooo... What does a List look like in Python?
A: a list begins with an opening square bracket and ends with a closing square bracket, []
example: sith = [ 'Vader', 'Palpatine', 'Maul', 'Dooku']
Values inside the list are also called items. Items are separated with commas.
The sith variable is still assigned only one value: the list value. But
the list value itself contains other values. The value [] is an empty list that
contains no values, similar to '' , the empty string.

Q: So how do I call items from the list in my program?
A: so we have [ 'Vader', 'Palpatine', 'Maul', 'Dooku'] stored in the variable sith, The Python code sith[0] would evaluate to 'Vader' , and sith[1] would evaluate to 'Palpatine', and so on. The integer inside the square brackets that follows the list is called an index. The first value in the list is at index 0, the second value is at index 1 and so on...

Q: Cool ! Can I use that in a string?
A: yes you can ! for example: print('Lord ' + sith[0]) will return Lord Vader
note: if you type a number not associated to a item in the list, you will get a Index Error : List out of range

Q: All that is nice but what about the List of List you mentioned?
A: Lists can also contain other list values. The values in these lists of lists
can be accessed using multiple indexes, like so:
sith = [['Lord', 'Emperor', 'Darth', 'Count'], ['Vader', 'Palpatine', 'Maul', 'Dooku']]
now you can print(sith[0][0]) which will print Lord
The first index dictates which list value to use, and the second indicates
the value within the list value. If you only use one index, the program will print
the full list value at that index. : print(sith[0]) returns 'Lord', 'Emperor', 'Darth', 'Count'

Q: That makes sense ! Can I put these lists together to make strings ?! You know like sentences or whatever?
A: Yup ! Time for some Code Snippets Challenge !!!

We will use some of the code from Ep.1 Introduction along with these lists to get some cool interaction !

from time import sleep

sith = [['Lord', 'Emperor', 'Darth', 'Count'], ['Vader', 'Palpatine', 'Maul', 'Dooku']]

print('Is ' + sith[0][1] + ' ' + sith[1][1] + ' in Rogue One the Movie?')
sleep(2)
print('Rumor has it that he caputured ' + sith[0][2] + ' ' + sith[1][2] + '\nand placed him in the bacta tank!')
sleep(2)
print('Spoiler Alert!!!' + sith[1][3] + ' is Supreme Leader Snoke reborn !!!')

Here is the challenge for you... Combine what you learned in Ep.1 print() input() time with this code snippet and lets see what crazy code you can come up with !

Stay tuned Code_Warriors

7 Likes

Not sure whether it was mentioned previously in Ep1. but it is possible avoid having to use a backslash (\) to write an apostrophe by enclosing a string (a sequence of characters e.g. 'A String') in quotation marks (") ("A string enclosed in quotation marks") instead of apostrophes. However this prevents you from using quotation marks inside the string.

Another version of the string is the one enclosed in three quotes ('''A sting
in three quotes'''
) which allows you to make a sting on multiple lines!

Anyhow, here is my version of the code:

from time import sleep

sith = [['Lord', 'Emperor', 'Darth', 'Count'], ['Vader', 'Palpatine', 'Maul', 'Dooku']]

print('Do  you think ' + sith[0][1] + ' ' + sith[1][1] + ' in Rogue One the Movie?')
Answer = input()
print("Well, I don't care what you think. Rumor has it that he caputured " + sith[0][2] + ' ' + sith[1][2] + '\nand placed him in the bacta tank!')
sleep(1)
print("Hey, you wanna hear a spoiler?")
Answer2 = input()
print('''Can't believe you fell for this again!
I said that I don't care what you think!
So, the spoiler is that ''' + sith[1][3] + ' is Supreme Leader Snoke reborn !!!')
sleep(10)
print('Just kidding, it is all just a theory!')
sleep(4)
1 Like

This is true and a good point.

Thanks ! I was hoping for community members to contribute, so I purposly missed some of the introductory things.

Ok so here are my two cents. As @Miguel_Sensacion showed us in the upper example python have 0 based index, meaning its starts from 0, so the 3rd item in the list will have index number 2. But you can also count backwards with negative index and its starts from -1.

    # Create the areas list
    areas = ["hallway", 11.25, "kitchen", 18.0, "living room", 20.0, "bedroom", 10.75, "bathroom", 9.50]
                [0]      [1]      [2]      [3]      [4]        [5]     [6]       [7]     [8]       [9]
               [-10]    [-9]     [-8]     [-7]     [-6]       [-5]     [-4]      [-3]    [-2]     [-1]

So you can also call your data from your list like that

# Print out second element from areas
print(areas[1])

# Print out last element from areas
print(areas[-1])

#Print out the area of the living room
print(areas[-5])
1 Like

@Pobs thanks for the contribution !

Fun using 2D arrays.

class noughtsAndCrosses:
    def __init__(self):
        self.board = [[" " for x in range(3)] for y in range(3)]
        self.players = ["X", "O"]
        self.turn = 0
        self.moves = 0
        self.won = False

    def play(self):
        self.intro()
        
        while self.won == False and self.moves < 9:
            self.makeTurn()
            self.checkLines()

        print("\n----------END GAME----------")
        self.displayBoard()
        
        if self.won == True:
            print("\nPlayer {0} won!".format(self.players[self.turn]))
            
        elif self.moves == 9:
            print("\nDraw!")

    def intro(self):
        print("""Each of the two players takes turns to make a move.
In each move a player places their character on the grid.
THe first to get three of their characters in a line wins.
If all nine possible moves are made without anyone making a line of three, the match is considered a draw.
Coordinates are as follows:

1,1 | 2,1 | 3,1
---------------
1,2 | 2,2 | 3,2
---------------
1,3 | 2,3 | 3,3

----------START GAME----------""")        

    def makeTurn(self):
        print("\n----------MOVE {0}----------".format(self.moves))
        self.turn = (self.turn+1)%2
        self.displayBoard()
        print("\nIt's now player {0}'s turn!".format(self.players[self.turn]))
        x, y = self.getMove()
        self.board[y][x] = self.players[self.turn]
        self.moves += 1
        
    def displayBoard(self):
        print("\n"+"\n---------\n".join([" | ".join(self.board[y]) for y in range(3)]))

    def getMove(self):
        x, y = [-1, -1]
        validMove = False
        
        while validMove == False:
            invalidCoord = False

            try:
                x, y = [int(x)-1 for x in input("\nEnter an x and y coord for your move (X,Y): ").split(",")]

            except ValueError:
                print("Invalid input - must be two integers separated by a comma")
                invalidCoord = True
                
            if not invalidCoord and (x not in [a for a in range(3)] or y not in [a for a in range(3)]):
                print("Invalid coordinate. Coordinates must be in range 1-3 inclusive.")

            elif not invalidCoord and self.board[y][x] != " ":
                print("Invalid coordinate. A move has already been made here!")

            else:
                validMove = True
            
        return x, y
    
    def checkLines(self):
        for a in range(3):
            if self.board[a].count("X") == 3\
            or self.board[a].count("O") == 3\
            or [self.board[z][a] for z in range(3)].count("X") == 3\
            or [self.board[z][a] for z in range(3)].count("O") == 3:
                self.won = True

        if [self.board[a][a] for a in range(3)].count("X") == 3\
        or [self.board[a][a] for a in range(3)].count("O") == 3\
        or [self.board[a][-a-1] for a in range(3)].count("X") == 3\
        or [self.board[a][-a-1] for a in range(3)].count("O") == 3:
            self.won = True
            
game = noughtsAndCrosses()
game.play()
1 Like

very cool, Thanks for the contribution.

I just wanted to add to this that Python doesn't have real Array's. Its not a problem. Python lists are more dynamical and can do everything an array can do too. Only downside they cost more resources compare to real Arrays, like the ones in C.

So when you need an array in Python you are actually referring to a list()

3 Likes