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