Reputation: 13
When I create a list of arrays in Python and print out the result of the first index, why does it print the square brackets too?
people = [
["Fredrick", 23],
["Lorenzo", 13],
["Francesco", 13],
["Giovanna", 9]
]
print(f"{people[0]}")
Output: ['Fredrick', 23]
Upvotes: 0
Views: 1615
Reputation: 416
You defined an array with arrays as elements. That's why you get the array ['Fredrick', 23] when you access the first index of people array. This is equivalent with accessing the first item of the array
>> array = [10, 20, 30]
>> print array[0]
>> 10
In your case the first element is the array:
>> ['Fredrick', 23]
An alternative approach could be:
# map is another (more appropriate)
# data structure to store this data.
people = {
'Fredrick': 23,
'Lorenzo': 13,
'Francesco': 13,
'Giovanna': 9
}
for name, age in people.items():
# iterate through all map items
# and print out each person's name and age.
# Note: you need to convert the age from int to string
# in order to concatenate it.
print name + ", " + str(people[name])
Upvotes: 1
Reputation: 22544
You created people
which is a list of lists. Then you refer to the f-string f"{people[0]}"
. When you reference it, the expression people[0]
is evaluated and is found to be the list ["Fredrick", 23]
. That is then converted to a string--remember, this is an f-string. The double-quotes around Fredrick
are converted to single-quotes, according to the Python standard, where either single- or double-quotes may be used to denote a string but they are alternated for strings-within-strings. Python wants to put double-quotes around the entire string whenever its representation is needed, so to alternate the type of quotes, single-quotes are used. So the final f-string is
"['Fredrick', 23]"
Remember, what is inside the string is a representation of the list inside people
. Python adds the brackets so everyone knows that is indeed a list. Python could have done it differently, but this makes the list nature explicit, and the second rule in the Zen of Python is
Explicit is better than implicit.
So the brackets are shown. If you do not want the brackets, there are several ways to remove them. The simplest way to print that f-string without the brackets is probably
print(f"{people[0]}"[1:-1])
which prints
'Fredrick', 23
That code prints the string but removes the first and last characters, which are the brackets. If you do not understand Python's slice notation you should research it--this is one of Python's strengths in string handling.
Upvotes: 1
Reputation: 2557
people = [
["Fredrick", 23],
["Lorenzo", 13],
["Francesco", 13],
["Giovanna", 9]
]
Creates a list of lists, people[0]
gives the first value - which is the list ["Fredrick", 23]
. When printing a list python (by default) print the brackets as well.
Upvotes: 0