Home > Back-end >  Where did this 'number' variable come from in this for loop?
Where did this 'number' variable come from in this for loop?

Time:04-05

I saw this code and it makes the uniques list not have duplicate integers. All of the code makes sense to me except for the number variable. Why does this variable function in this code as so, despite not being specific to the list? Is it just representing the iterations of the for loop, so it checks the numbers list? Or am I missing something?

numbers = [56, 56, 66, 93, 66, 85]
uniques = []
for number in numbers:
    if number not in uniques:
        uniques.append(number)
print(uniques)

CodePudding user response:

numbers = [56, 56, 66, 93, 66, 85]
for number in numbers:
    print(number)

This is code for a 'for loop'. Here 'number' variable is individual number for each iteration. This code is looping through all the numbers in the list. And its output will be.

56
56
66
93
66
85

And if you use any other name instead of 'number' it will print the same result.

numbers = [56, 56, 66, 93, 66, 85]
for x in numbers:
    print(x)

CodePudding user response:

I'm not sure what exactly you're asking, so I'll break down the variables.

numbers is the list, containing [56, 56, 66, 93, 66, 85].

number is the number in the current index of the loop, so it for the first iteration of the loop it's 56, then 56 again, then 66, and so on. This is essentially redefining a local variable each time the loop loops, meaning that you can use it inside the loop.

Hopefully that answers your question.

  • Related