for loops – beginner question

Q & ACategory: Questionsfor loops – beginner question
Nico asked 3 years ago

Greetings!
I have recently started Python as my first computer language and there is one part of the for loops I am having trouble with.
The objective of the code below is to turn a list [1,1,2,3,3,3,4,4,5] into a list with only the unique elements of the first list. [1,2,3,4,5] without the use of sets.
code:
def unique_list(g): 
      x = [ ]
      for a in g: 
           if a not in x:
               x.append(a)
return x
 
I understand what each individual part of the code does but the part of “forin g” is what confuses me. I know “g” is the list in reference but what is “a”? If it is the elements in “g” how can Python tell the difference of each element, if I had numbers and strings and symbols?
 
Also, the below section is confusing in the sense of what the role of “a” is and how does it know which to append? I get that if an “a” similar to another “a” is in the list it will not duplicate it but how does it know which “a” to append?
code:
if a not in x:
               x.append(a)
 
My apologies for the long post and I hope what I asked is understandable. Any help would be greatly appreciated!
 
All the best,
 
Nico                 

Wes Turner replied 3 years ago

– collections.OrderedDict.fromkeys(g).values()
– dict.fromkeys(g).values()

https://wiki.python.org/moin/TimeComplexity

O

Wes Turner replied 3 years ago

… O(1) is much preferable to O(n) for ‘x in list()’

Nico replied 3 years ago

Thanks!

Wesley Turner replied 3 years ago

yw!

2 Answers
Steve - for Chad answered 3 years ago

So ‘a’ is essentially a temporary variable that is updated while walking the list.

for a in g:
   print a

would output
1
1
2
3
3
etc

So, keeping that in mind, if a conditional check to see what “a” currently is assigned
exists in the “x” list.  And as written, appends to the list if it is not seen in “x”

Hope that helps
Chad

Nico replied 3 years ago

Thanks a ton, this helped!

a answered 3 years ago

That line (for a in g) iterates through the list g, object by object. Each iteration reassigns the variable a. 
When creating an object class you can define how to compare them. This is how Python handles strings, integers, booleans, floats, /whatever else.
Comparator functions can be written to compare object properties. For example a custom object book, may have properties book.name and book.title 
For speed you could string compare on just the name, or you could do both for completeness. 
Objects can be casted to another object for example a number to a string. w
Reading some pdfs on object oriented programming would help. 
 

Nico replied 3 years ago

Thank you so much for all of the help, I didn’t think to go about it that way!

Your Answer

11 + 10 =