FAQ: Loops - While Loops: Lists

I don’t know if you are looking for an explanation, but in case someone bumps into this and wants one, here it it:

I understand you have the folowing code:

python_topics = [“variables”, “control flow”, “loops”, “modules”, “classes”]
#Your code below:
length = len(python_topics)
index = 0
while length < index:
print("I am learning about " + python_topics[index])
index += 1

Syntactically it is correct, but the best practice is to select the condition as the variable that will update within the loop.

I understand this is the reason from CodeAcademy they preferred to not accept this option.

Hi,

what purpose does [index] serve in the print statement?

print('I am learning about ’ + python_topics[index])

image

can this implementation of python do arithmetic on hexadecimal integers?

how do you make it print to the… terminal? in hex?
also, if it’s possible to print a list of items without the on one line, how?

>>> print (hex(65535))
0xffff
>>> print (f"{str(hex(65535))[:2]}{str(hex(65535))[2:].upper()}")
0xFFFF
>>> 

To print a list with the commas,

>>> print (f"{str(list('abcdefgh'))[1:-1]}")
'a', 'b', 'c', 'd', 'e', 'f', 'g', 'h'
>>> 

Down the rabbit hole…

>>> from functools import reduce
>>> print (reduce(lambda a, b: a + f", {b}", 'abcdefgh'))
a, b, c, d, e, f, g, h
>>>

rabbit hole indeed.
print a list on one line/print statement without any symbols(the brackets and commas)

1 Like

I have the exact same question but I don’t see a response! Anyone??? Please?

Python lists are zero-indexed i.e. the first element is at index 0, the second element is at index 1 and so on. To access a specific element of a list, we can do so by writing the list’s name followed by square brackets with the index of the element we want to access.

myList = ["a", "b", "c", "d", "e"]

# Printing second element of list
print(myList[1])
# "b"

# Printing fourth element of list
print(myList[3])
# "d"

In the exercise, python_topics is a list whose elements are strings.

python_topics = ["variables", "control flow", "loops", "modules", "classes"]

A while loop is being used in the exercise to iterate over the index i.e. in the first iteration, index will be 0, in the second iteration, index will be 1 and so on.
But we don’t want to print the index. Instead we want to print the element at that particular index.
python_topics[index] will allow us to access the string element at that particular index.

print('I am learning about ' + python_topics[index])

In each iteration of the while loop, the + operator will concatenate/join the string 'I am learning about ' with one of the string elements so that we get outputs such as:

"I am learning about variables"
"I am learning about control flow"
...