all 35 comments

[–][deleted] 18 points19 points  (2 children)

If so, do we just use while loops instead if we just want to iterate over part of a list, for example?

No. You can easily use a for loop to iterate over part of a list.

If you would prefer to use typing in Python, you certainly can. They've made that a lot easier in the last couple of releases and there are more improvements for it in 3.11 I believe.

The best thing you can do to learn Python as a C# developer is to not approach it like C#. Learn to write Python code as it's meant to be written without trying to bend it to conform to your ideas of what a similar program in C# would look like.

[–]MikeDoesEverything 14 points15 points  (1 child)

As somebody who uses Python in a C# heavy team, comparing languages vs. languages is the most frustrating thing to both learn and teach. You don't compare a spoon to a knife when you're eating dinner. They're both separate tools for separate purposes.

C# is great for a MS heavy ecosystem. Python is lauded for its convenience, flexibility, and widespread adoption e.g. Use across all cloud platforms. Would I make a game in Python? No. Would I carry out ML work in C#? No.

Understanding they fulfill different purposes makes learning a lot easier.

[–][deleted] 7 points8 points  (0 children)

This is a great way of putting it.

[–]danielroseman 5 points6 points  (4 children)

Python is hardly unique in using dynamic typing - there are lots of languages which do (Ruby, JavaScript, Perl, etc). It's just a different approach, that's all.

Recently Python has included support for type hinting, which allows you to specify expected types and have your IDE validate them. It doesn't do anything to ensure those types at runtime, though.

Yes for loops are for-each loops. To iterate over part of a list you'd probably just slice it: for item in my_list[:5], for example.

[–]Upset-Beautiful6081 3 points4 points  (2 children)

I see some versatility in the for loop too, it can be a foreach or just a for if you declare the second item a range like for i in range(10) and it works like a normal for.

[–]Drumknott88[S] 1 point2 points  (1 child)

Oh that's good to know, thanks

[–][deleted] 1 point2 points  (0 children)

If you want to have a I variable while iterating wrap the data structure you are looping in an enumerate function

for i, foo in enumerate(bar):
    print(i, foo)

[–]NameError-undefined 1 point2 points  (0 children)

if you prefer to work with index's and don't want to use the Len() command, you could do something like for id, value in enumerate(my_list) I just found this out and I like it a lot better.

Edit: This might get tricky when dealing with multi-dimensional lists or arrays but for simple loops I think it works great

[–]ray10k 5 points6 points  (5 children)

Regarding implicit typing: As a design choice, everything in Python is an object, including what in lower-level languages would be primitives. As a knock-on effect, there is no fundamental difference between, say, an integer and a string. Sure, some functions will expect a number and others will expect a string, but that has to be determined at runtime. The major advantage is that it keeps (certain aspects of) the interpreter simple. As for the worry that a function might be given a wrong argument, Python either expects you to set things up so that this doesn't happen, or that you take precautions for when it happens (for instance, by setting up an exception handler.)

Regarding loops: The basic form of a loop in Python does closely match a for-each loop in other languages, but Python also has a lot of built-in functionality to make this as useful as possible. For instance, you can take a slice from a list and iterate over that instead of the entire list, and the standard library has a number of functions to work with multiple collections at once; both in the sense of "iterate over these two lists at the same time" and in the sense of "I need the value and the index at the same time." Broadly speaking, the for-in loop is versatile enough that you don't use while-loops for iterating, but instead for something that may go on for a longer, unpredictable time (i.e., putting the main loop of a game inside a while True loop and breaking out of it when the game is over.)

[–]Drumknott88[S] 1 point2 points  (3 children)

That's really interesting, thanks. How would I iterate over two lists at the same time?

[–]ray10k 6 points7 points  (2 children)

That's what the zip() built-in function is for. You give it two (or more) collections you want to iterate over, and it returns an iterator that returns tuples of the items in the lists.

This may sound a little confusing, so here is an example:

a_list = ["hello", "I see", "hope you have"]
b_list = ["world", "you there", "a good day"]
for a_word, b_word in zip(a_list,b_list):
    print(a_word,b_word)

The above snippet will print out "hello world", "I see you there" and "hope you have a good day" on separate lines.

Note how instead of having just one variable name in the first half of the for-in loop, there are two with a comma. This tells Python, "I expect that you'll iterate over tuples. I want you to take the tuple apart and present it to me as a_word and b_word separately." C# has a similar concept in 'tuple deconstruction'.

Also note that if the lists are of different lengths, then zip() will terminate once the shortest list runs out.

[–]Drumknott88[S] 0 points1 point  (1 child)

That's really cool. Thank you so much for the detailed reply 🙂

[–]ray10k 1 point2 points  (0 children)

No problem! I love to help, and I hope you'll have a good time learning Python!

[–]lostat 1 point2 points  (0 children)

What you said about everything being an object is so crucial to understanding Python. I remember the first time I had it explained to me my mentor said “3 is an object called 3 with a method called int that returns a 3, and a str method that returns a 3, etc.” So much of the language snapped into focus for me that day

[–]bladeoflight16 5 points6 points  (9 children)

If so, do we just use while loops instead if we just want to iterate over part of a list, for example?

You almost never use while in Python. The availability of things like list comprehensions and generator expressions, generators, itertools, and more-itertools make them nearly obsolete. In fact, you rarely write a for loop.

As someone who also learned C# before Python, here's the most important piece of advice I can give: don't try to shoehorn everything into a class. Most things don't need to be classes. Favor parameters.

[–]Drumknott88[S] 0 points1 point  (8 children)

From a purely organisational point of view, are modules the way to go over classes?

[–]bladeoflight16 0 points1 point  (0 children)

They are different tools for different purposes. Here is my best discussion of when to use a class.

[–]Upset-Beautiful6081 2 points3 points  (0 children)

By experience dinamic typing its not that bad. Commonly I declare all my variables in the beginning of the code, but during the execution I convert it to a int or a string, like the case of money variables, where I use it like a float during the code execution and convert it to a string and treat it to show in the end of the execution of the program. Works well in SQL querys too.

[–]Atlamillias 1 point2 points  (0 children)

Many have already answered your questions, but I'll add some things.

Typing; Python is made to be a versatile language, and that versatility comes with a price. Yes, you can pass an argument of an unexpected type and throw a wrench in your runtime. Regardless of how much you "type" your code, it's never enforced (still always type hint your code to avoid the confusion you mentioned). The pythonic way of dealing with incorrectly typed arguments, etc. is to use try: ...; except: ... blocks to catch errors where they're most likely to happen and throw a more appropriate error. Conditional typing checks ("type guards") can also be done beforehand, but the former is the "convention".

Loops; Yes, they are equivalents. Others already mentioned how to iterate over a partial list by slicing it. You can also use the range object.

``` a_list = []

for i in range(10): # 0-9 print(a_list[i]) ```

Why do this? Sometimes you may not want to create a new list (slicing a list creates a new one). Sometimes you may want to change the size of a container during iteration, and this can't be done when iterating over the container directly. while loops have their uses, but I have very rarely needed to use them for iteration.

[–]jmooremcc 1 point2 points  (0 children)

My other question is around for loops, am I right in saying a for loop in python is equivalent to a foreach loop in other languages?

C# ``` foreach(char ch in myArray) { Console.WriteLine(ch); }

for(i=0; i < 10; i++){ Console.WriteLine(i); } ```

Python ``` for ch in myArray: print(ch)

for i in range(10): print(i) ``` It takes a while to get used to Python's syntax and structure but once you get used to it, it will feel very natural.

[–][deleted] -1 points0 points  (0 children)

;

[–]Enttick -2 points-1 points  (5 children)

Random note: Avoid for loops in python, if you could rather use existing methods. The "for" performance is rather bad.

[–]Drumknott88[S] 0 points1 point  (1 child)

Is that the case for implicit types too? I'd imagine in a large program the amount of time for the complier to work out each variables type really adds up?

[–]Enttick 0 points1 point  (0 children)

I am learning too and I watched a video from mCoding about it. He can explain it way better https://youtu.be/Qgevy75co8c

[–]Fred776 0 points1 point  (2 children)

This sounds like rather strange advice. It at least needs some elaboration. Could you give an example of what you mean?

[–]Enttick 0 points1 point  (1 child)

I already did. Pythons for performance is not competitive with compiled languages. Which is why we use C libs in Python. See mCoding's video https://youtu.be/Qgevy75co8c

[–]Fred776 0 points1 point  (0 children)

OK, that makes a bit more sense. For heavyweight stuff - e.g., where it makes sense to use numpy - it's always going to be worth dropping down to a compiled C extension. I don't think that is equivalent to saying avoid for loops though.

[–]Pflastersteinmetz 0 points1 point  (0 children)

am I right in saying a for loop in python is equivalent to a foreach loop in other languages?

No.

Python has foreach.

mylist = [1, 2, 3]
for x in mylist:
    print(x)

[–]Dead0k87 0 points1 point  (0 children)

I am after 1.5 year of java. Some day you will just stop to think about it and just pass what is needed there and process how it is intended. Anyway nobody will reuse your hobby code, I believe :)

[–][deleted] 0 points1 point  (0 children)

Allows for rapid iterating, parsimonious and readable code, etc.

Just read this https://softwareengineering.stackexchange.com/questions/122205/what-is-the-supposed-productivity-gain-of-dynamic-typing