Python Tutorial: Comprehensions - How they work and why you should be using them

Corey Schafer · 588K views · 2015 · 18:29

Open on YouTube

Python, Ruby & scripting languagesEducation & learningtutorial

Why Stack Overflow recommends it

Stack Overflow users link it when an answer uses a list or dict comprehension and the asker may need a clear introduction to the syntax.

Recommended by 5 people across 4 different months, 2020 to 2023.

What it is

Corey Schafer's Python tutorial explains list, dict and set comprehensions, showing how they work and how they compare with for loops, map and filter. It walks through examples with code available on GitHub.

What people said

Recommends Akiem Paul · 2020-10 · Stack Overflow · on “Python - construct set with for loop”

Ok not sure which part of the code you were referring to. def solution(**paths**): #1 s = set(p[0] for p in paths) #2 #1 creates a function called solution, that takes one argument (path) #2 assigns a set to the variable s . set( ) is a function creates a set object. p[0] is the item you want from the forloop. and you are grabbing the first variable in each set that is in path it can also be interpeted as: def solution(paths): s = {} # declare variable for item in path: # use forloop s.add(item[0]) #add the first element of each item in path (the set in path) print(s) test_path = [ ['a','b','c'] , ['a','e','f'], ['g','h','i'] ] solution(test_path) notice in the results printed below that onl

Recommends Noob_Code · 2020-10 · Stack Overflow · on “Creating a Dict for the name and a list of the values from a CSV file”

The for loop with enumerate will get ind as the index of the line and the variable row is the data on that line. The strand is the first line on the csv_file and a list comprehension is being run on that line. If you aren't sure what a list comprehension is, here is a link explaining: [LINK] The row.strip() function will remove all whitespace. The .split(',') function will turn that line in the csv_file into a list of items separated by the ',' comma. So strand would be ['name', 'AGATC', 'AATG', 'TATC']. The curr_row is doing the same thing with the following lines. So line 2 in the csv_file is: Alice,2,8,3 After running, curr_row = row.strip().split(',') on the second line, curr_row will eq

Recommends Ajay Singh Rana · 2021-08 · Stack Overflow · on “Find common id between a list and a list of tuple”

You just need to traverse the list with id's and names and compare the id's with the elements of the list of id's.If these match then you can append these to the names list: ids = [555,567,597,589] names = [(555, 'name1'), (577, 'name2'), (567, 'name6')] common_ids = [] for i in names: if(i[0] in ids): # to comapre ids stored inside the tuple with elements in the ids list common_ids.append(i[1]) print(common_ids) Output: ['name1', 'name6'] And if you are comfortable with list comprehensions you could do all of the above in just one line: ids = [555,567,597,589] names = [(555, 'name1'), (577, 'name2'), (567, 'name6')] common_ids = [i[1] for i in names if (i[0] in ids)] You could learn list co

Recommends Conor · 2022-08 · Stack Overflow · on “how to write a line to read a certain sentence in a text file?”

List comprehensions in python: [this video] Using list comprehension with files: [LINK] First learn list comprehensions, then the idea is this: listOutput = ['''min = 32.421 text = "Hello I am Robin and I am hungry" max = 233341.42'''] myText = ''.join(listOutput) indexFirst= myText.find("text") + 8 # add 8 to this index to discard {text = "} indexLast = myText.find('''"''', indexFirst) # locate next quote since indexFirst position print(myText[indexFirst:indexLast]) Output: Hello I am Robin and I am hungry

Recommends Sajil Alakkalakath · 2023-03 · Stack Overflow · on “how to convert csv data into list of {key : value} pair?”

load the data df = pd.read_csv("yourfilename") Use the list comprehension. I am using zip function as well. mydict = {val1:val2 for val1,val2 in zip(df.iloc[:,0],df.iloc[:,1])} There is a good youtube content from Corey schager about list comprehension: [this video]