r/learnpython • • Feb 20 '21

What are you having difficulty learning or are currently struggling to learn?

I'm curious what the community here has difficulty with when it comes to learning Python. Partly because I want to see if the more experienced community here (or myself) can help point you into the right direction. . . but also because I'm trying to come up with video tutorial ideas for future content and would love to hear from Python learners what would be most useful to dedicate our time on.

I'm looking forward to hearing what you guys have to say!

417 Upvotes

324 comments sorted by

View all comments

1

u/Athenas-Helm Feb 20 '21 edited Feb 20 '21

Still very much a beginner, but comparing similar values between two lists (and returning a list of common values) is throwing me through a loop and feels a decent step up from other things I've practiced. Is there a better solution than

 indexor = 0
 common_list = []
    for element in list1:
        if list1[indexor] in list2:
            common_list.append(list1[indexor])
            indexor += 1
        else:
            continue
return(common_list)

2

u/Nythious Feb 20 '21

There's a very sexy way to do this if you convert those lists into sets but if you're destined to using lists then you'll want to switch out "if list1 blah in list 2" with "if element....". That's my hint for you. Edit: on my phone, sorry about terrible formatting!

2

u/Athenas-Helm Feb 20 '21
common_list = []      
    for element in list1:          
        if element in list2:              
            common_list.append(element)             
        else:              
            continue  
return(common_list)

1

u/Athenas-Helm Feb 20 '21

The append(element) syntax might not be right but the concept is what i'm trying to grasp generally lol

EDIT: thank you for the advice!

2

u/keraj93 Feb 20 '21

I assume that the code is a part of a function, otherwise, the return statement will cause an error

if you iterate directly over the elements with for element in list1 then you don't need the indexor. You can use the ´elementto check the if statement, like this:if element in list2:and common_list.append(element).

Also a shortcut: intersection = list(set.intersection(set(list1), set(list2))) `

1

u/Athenas-Helm Feb 20 '21

Thats what I went for with my revision so good to know!

Thank you for the shortcut as well

1

u/sje46 Feb 20 '21

Definitely use sets for this!

1

u/Athenas-Helm Feb 20 '21

I see the appeal for sets, the codewars challenge had it in lists but will keep this in mind!