Questions tagged [list-comprehension]

A syntactic construct which provides a concise way to create lists in a style similar to the mathematical set-builder notation. Since several languages support list comprehensions, please use this tag in conjunction with the tag of a programming language.

Filter by
Sorted by
Tagged with
-1 votes
1 answer
30 views

Python: altering items in a list when the list is a value of a dictionary [closed]

This may sound simple, but I can't wrap my head around it. My dictionary: MY_DICT = { "foo":[ "bar/", "baz" ], "another_key": [ ...
cyclopticnerve's user avatar
1 vote
5 answers
51 views

Mixed type list comprehensions in Python

im trying to filter a list for numbers greater than a certain value whilst keeping any strings in the list. Id like to acheive this without a loop, so preferably a list comprehension. So far i have ...
Callum Brown's user avatar
-2 votes
1 answer
55 views

Python Problem i am preparing myself for PCEP Exam [duplicate]

my_list = [x * x for x in range(5)] def fun(lst): del lst[lst[2]] return lst print(fun(my_list)) why is the answer [0,1,4,9] As far as what I understand : first part : 0*0 1*1 2*2 3*3 4*4 ...
Marko Kostic's user avatar
1 vote
3 answers
35 views

how to check if element of list contains one of the elements of another list

I have a list of strings ['asdf', 'qwer', 'zxcv'] and I need to return a list containing the elements of this list which contain any of the strings in ['a', 'g', 'y']. I have attempted this with the ...
Nikko Cleri's user avatar
1 vote
6 answers
39 views

How to split DataFrame rows at Nth character in a column?

I have encountered a scenario where in a column I have the possibility of 0,2,4, or 6 character strings that I need to expand into 1,2, or 3 rows, as follows: Current Employee Pay Grade John 7A5B ...
datagolfer's user avatar
0 votes
1 answer
49 views

How to use a list comprehension to make the first item in a nested list 0?

For example if I have a list that is something like: num_list = [ [1234, 1244123, 453242], [123123, 78421, 76433], [46345, 578542, 47463] ] and I need it to return [ [0, 1244123, ...
Jacob Mathew Keluthara's user avatar
1 vote
1 answer
54 views

Need help converting a list comprehension to a lambda function

I am learning lambda functions and I came across a question which is actually meant to be solved using a list comprehension but I wanted to know if there is a way to do the same using lambda functions....
rpicoder's user avatar
0 votes
0 answers
26 views

how to change output of lambda function in filter + lambda?

I am a beginner in python and currently I am learning how lambda functions work. I want to know if there is a way for me to influence the output of a lambda + filter combo, because if I have ...
rpicoder's user avatar
1 vote
3 answers
35 views

Pandas Assign, Lambda, List Comprehension Question

I receive data as a list of dicts in a single column. Each list can be a different length. Sample data looks like this: df = pd.DataFrame( [ [[{'value': 1}, {'value': 2}, {'value': 3}]], ...
John Duffy's user avatar
0 votes
1 answer
31 views

Accessing object generated within a list

So i've been practicing with OOP in python and decided to take a program i wrote before and update it using OOP methodology. Basically it's a game where it will ask you how many players you are ...
Charlie Jandura's user avatar
1 vote
3 answers
31 views

How can I avoid indexError using list comprehension in python

I have an array of dictionaries and I want to check if a particular key is in the array of dicts and retrieve the item. I know how to do this using list comprehension but is there a way to avoid ...
oj43085's user avatar
  • 127
-1 votes
2 answers
76 views

Python List -- ValueError: invalid literal for int() with base 10: ' ' [duplicate]

I have tried to use both loops as well as list comprehension. Both are unable to parse the integers even though i am trying to convert the numbers into int in a list. student_scores = input("...
Rajesh's user avatar
  • 41
0 votes
1 answer
30 views

Create a list from another list in Python, where [i] in list2 = is a counter of list1

From list1 list1 = [1654, 2175, 2478, 2132, 2250, 2304, 2258, 2111, 1683, 2036, 2089, 1743, 1920, 1854, 2251, 1505, 1698, 1126, 1695, 1590] I would like to create a second list (list2) which would ...
Jackfin321's user avatar
2 votes
1 answer
46 views

Create dataframe with list comprehension with each column dependent on the previous

I need to create a dataframe with list comprehension whereby each column is equal to a transformation of the previous one. However, each column is not dependent on the previous. I only have the first ...
flowover9's user avatar
1 vote
2 answers
71 views

python list comprehension: list of dicts to dict of lists with key intersection

I have a list with a variable number of dictionaries, for ex: var = [ {'a': 1, 'b': 2}, {'b': 20, 'a': 10, 'c': 30}, {'c': 300, 'a': 100} ] I need to extract the keys that are common to all dicts, ...
Fravadona's user avatar
  • 14.2k
1 vote
1 answer
37 views

Compare Nested List With Different Index Amount and Same Condition in Particular List

i have two nested list and the result data1 = [ ["tr1", 1002, 6798381], # return false ["tr1", 1001, 6798381], # return false ["tr1", 1001, 6798381], # return ...
Yogyakartas's user avatar
-4 votes
2 answers
59 views

Creating Two Level List Comprehension in Python

Here's a brain tickler that I have been trying to solve for a couple of hours. The code below takes two lists of integers and returns a list of the items in the 1st list but not the second AND the ...
Sean Massey's user avatar
-3 votes
1 answer
48 views

Not understanding Python List Comprehension

t = [[3-i for i in range(3)]for j in range(3)] s = 0 for i in range(3): s += t[i][i] print(s) Eventually the result should be 6.Can please someone explain me the whole proccess and why is ...
Marko Kostic's user avatar
0 votes
2 answers
96 views

Python code optimization, list comprehension, lambda function

Please help. I have these for loops: path1 = None for key, value in items: if key.func1() == a and value == b: path1 = key.func() break ...
John Doe's user avatar
0 votes
2 answers
44 views

Python list of comprehension, lambda function

I have this old version: for item in items: if not [True for key, value in items if a = b and c = d]: if fail: return False else: ... But now I added ...
John Doe's user avatar
-1 votes
1 answer
36 views

How to do this with list comprehension in Python?

I have a list of tuples that I want to convert to integers using a dictionary, I think this can be done in one line but cant figure it out and I am instead using explicit for loops, anyone know how? ...
onion117's user avatar
-1 votes
2 answers
45 views

Apply function with two arguments on same list and output only lower/upper triangular matrix without diagonal

I want to compare strings without unecessary comparisons, so far I have: [[[dice_coefficient(x,y) for x in ['a','a','b'][j]] for y in ['a','a','b'][0:j]] for j in [1,2]] where dice_coefficient is ...
user1627466's user avatar
4 votes
6 answers
91 views

Using a list comprehension with "if" to create a list of items without duplication

I have a list word_list = ['cat', 'dog', 'rabbit']. I want to use list comprehension to print each individual character from the list but removes any duplicate character. This is my code: word_list = [...
Huy Trương Quang's user avatar
0 votes
0 answers
33 views

Why my list comprehension doesn't work with a plot and datetime? [duplicate]

I'm making a plot using matplotlib and trying to use list comprehension. When I use only one argument for ax.plot(highs), it works: import csv from datetime import datetime import matplotlib.pyplot ...
Local man's user avatar
0 votes
2 answers
45 views

My answer is not running for one of the sample

I wrote this python3 code using list comprehensions, my code is running fine for one of the samples, but showing one extra list in the answer as it can be seen in the picture attached. It's showing [1,...
Kashvi's user avatar
  • 13
0 votes
3 answers
49 views

Code Review Cumulative Totals of List Taking Snapshots at Index Python

another question about cumulative totals. Consider the following code: json_message = {'result':[[12, 234], [53, 45], [3, 425], [74, 12], [3, 678], [2, 42], [12, 234], [1, 66], [6, 85]...
led_farmer's user avatar
0 votes
1 answer
35 views

Check intersection between each element in array of lists

In Python, I have a list of different size arrays. I would like to know the intersection for all arrays contained in the list. For instance: import numpy as np array0 = [0,1,2,3,4,5,6] array1 = [0,2,...
AaronJPung's user avatar
  • 1,105
-8 votes
1 answer
78 views

How can I make this loop a single line? (list comprehension) [closed]

I want to make this piece of Python code (loops) just a single line, but I don’t know how. My goal in this project is to prove that not always the smaller the code (in number of lines) the better, ...
Guilherme Salmi's user avatar
-1 votes
1 answer
49 views

In Python, how do I create a list from a .csv file in such a way as to avoid commas inside quotations while separating using commas

I'm completely stumped. Here are the contents of my .csv file: [('54th St. & Ray Rd., Chandler,"Chandler, AZ",AZ,Yes,3/29/2022,6/9/2022,72,1,9,10,17,0.5882, -0.8000,0.1000,No')] When I ...
BBD's user avatar
  • 1
-2 votes
2 answers
50 views

Use a list comprehension to concatenate each item in list to a substring and store as a dictionary

I want to use a list comprehension to concatenate the strings in metadata.index.to_list() to the : set() substring and store them as `` dictionary. The length of the list is undefined and the ...
melolili's user avatar
  • 1,279
-1 votes
2 answers
45 views

Break out from For loop in List Comprehension

I'm trying to below code in line, and looks like List comprehension doesn't support break. Just trying to see if there is anyway we can implement below code in one line. Basically if commonprefix is ...
user14932992's user avatar
0 votes
1 answer
54 views

How to write a for loop or list comprehension that iterates over a column of strings and returns a Boolean or a category in a new column from a list?

I have a data frame with multiple columns, one of which contains strings separated by spaces -- these strings are titles for property listings and have upper and lower case words. I'm trying to write ...
new_to_code's user avatar
2 votes
2 answers
35 views

Automatically send all elements in list inside of a for loop list comprehension into a function

I access a function via this list comprehension and have made it work by explicitly creating a variable for each element of the list_of_lists. I want a better way to access the elements in the ...
user2403531's user avatar
-3 votes
4 answers
68 views

Remove "A-Z." from every list entry if it's there in Python

Sorry this might be an easy question but struggling to find a best way. I have list like below, and am wanting to remove all parts that contain any letter and a . afterwards. So I want to transform ...
knight's user avatar
  • 39
0 votes
1 answer
84 views

List comprehension: avoid the warning 'Cannot access member "get" for type "list[Unknown]"'. How to?

I'm trying to clean up a tiny bit my python code and remove as many as Pylance warnings (albeit the code has been tested and it works). Particularly, I'm struggling with the following one. I've my ...
Andrea Moro's user avatar
1 vote
1 answer
34 views

How to append an else case to a dynamically created case statement in sqlalchemy?

Say I have a list of thresholds with corresponding classes like this: classes = [{1, "1"}, {2, "4"}, {3, "7"}, {4, "8"}, ...
Ipsider's user avatar
  • 553
0 votes
1 answer
74 views

How to merge single-column pandas data frames in Python?

I want to merge the dataset into a 1432 rows x 4 columns data frame. After I used for loop function to filter the all data, the output was separated into 4 outputs, each 1432 rows x 1 column. However, ...
TCC's user avatar
  • 13
1 vote
1 answer
24 views

How can i sum the elements of the list in the nested dictionary

I have an dictionary as below dict= { ('201', '1'): {'357': [1, 67500], '360': [1, 40000], '362': [2, 45000], '365': [1, 12500]}, ('301', '2'): {'322': [5, 237500]}, ('301', '1'): {'325': [10, 675000]}...
SH Chung's user avatar
1 vote
2 answers
46 views

Taking into account weekends/holidays when using timedeltas in pandas

So heres a problem it took me a while to figure why its happening... I have a dataframe of values with a datetime index of workdays. Im adding a new column, 'ColB', which is always the same value as ...
AndysPythonStuff's user avatar
-1 votes
2 answers
26 views

TypeError: Medal.__new__() missing 3 required positional arguments: 'athlete', 'team', and 'event

--------------------------------------------------------------------------- TypeError Traceback (most recent call last) Cell In[19], line 1 ----> 1 medals =[Medal(...
ian daniells's user avatar
0 votes
1 answer
34 views

using Break with list / dictionary comprehension in Python [duplicate]

I want to get the grades of student based on there marks, while using for and if i can use break when the first time numbers are greater the specified grade the program is numb = int(input(&...
Kamran Asghar's user avatar
0 votes
2 answers
41 views

Transform solved code using loop and conditionals to list comprehension

I have this code already solved using traditional methods: edades = [10, 25, 49, 16, 60] mayores_edad = [] for edad in edades: if edad >= 18: mayores_edad.append(1) else: ...
pab1994's user avatar
0 votes
1 answer
35 views

List comprehension with conditional expression omitting some cases

I have list of bonds between points (as pairs of indexes) and index of a pivot point. I want to list of points bonded to that pivot point irrespective if it is on the first or the second position (I ...
Prokop Hapala's user avatar
3 votes
2 answers
100 views

How to remove a tuple in an integer tuple, if its last element is "0", using Python itertools?

I have the following code to create a tuple contains multiple tuples with integer pairs: iterable = ( tuple(zip([0, 1, 2], _)) for _ in product(range(9), repeat=3) ) next(iterable) # First ...
serhatcelik's user avatar
3 votes
2 answers
70 views

Dodgy List comprehension: should this code be accepted?

comp5 :: [ Either Int Int ] comp5 = [ Right x | {- Just y <- Just 2, -} let x = 5, y <- [x, undefined] ] -- ^^ rejected: RHS must be list, `let` accepted ...
AntC's user avatar
  • 2,643
0 votes
2 answers
44 views

Why can't I check if a string is a substring of each string in a list by using list comprehension?

I have the following code: MFII_files = ['patrick', 'domccc', 'joseph', 'harry'] file_name = 'ccc' if file_name in MFII_file for MFII_file in MFII_files: print('yes') But when I run it, it ...
ifrj's user avatar
  • 97
1 vote
1 answer
33 views

How to add labels in panda dataframe columns with else condition?

I have a dataframe with a column like this: POLITICS BUSINESS TRAVEL SPORTS .... DIVORCE ARTS WELLNESS CRIME e.g import pandas as pd data = [['CRIME', 10], ['BUSINESS', 15], ['...
Bluetail's user avatar
  • 1,115
0 votes
1 answer
28 views

Conditionals with possible None values in List comprehension

I have a xml file that lists speakers: <speakerlist> <speaker> <title>Dr.</titel> <firstname>Bernd</firstname> <lastname>Baumann&...
Quantum's user avatar
  • 510
1 vote
1 answer
27 views

how to condense this code into one single line?

Given this array: arry = [[111,2],[3,4],9] I am trying to get this code segment condensed into a single line: for index,item in enumerate(arry): if isinstance(item,list or np): for index2,...
mat you's user avatar
  • 15
0 votes
1 answer
94 views

set() inside list comprehension inefficient?

I'd like to compute the difference between two lists while maintaining ordering. ("stable" removal): Compute a list that has all values from list contained in b removed from list a while ...
LetMeSOThat4U's user avatar

1
2 3 4 5
142