Hello World!
We have a list like
>>> people = ["John","Jack","Jim"]
Let's say we want to add a number next to each one of this name.
we could use this way
------------------------------- code ------------------------
Yes... but we will talk about this in the next blog.
We have a list like
>>> people = ["John","Jack","Jim"]
Let's say we want to add a number next to each one of this name.
we could use this way
------------------------------- code ------------------------
people = ["John","Jack","Jim"]
x = 0
for names in people:
people[people.index(names)] = people[people.index(names)] + " " + str(x)
x += 1
print(people)
-------------------------------------------------------------
otuput: ['John 0', 'Jack 1', 'Jim 2']
--------------------------------------------------------------
Let's explain it a little bit.
withfor names in people:
we iterate the list "people", right?
We go through "John","Jack" and "Jim"...
to add the number ...we used this system: to find the index of each name in people and then use this
index to change the value adding the 'x' variable (transformed in string with str(x), because you can't add
a number to a string)
Is there another way?Yes... but we will talk about this in the next blog.
Comments
Post a Comment