-3

Hello I'm new to python and want to make a the for loop more concise using the list comprehension method these are the below. What is a way that I can do that?

if isinstance(value, list):
    new_value_list = []
    for item in value:
        replaced_text = substitute_jirae_text(item)
        new_value_list.append(replaced_text)
     section_dict[key] = new_value_list
else: 
Yavier
  • 1

4 Answers4

0

what about this?

new_value_list = [substitute_jirae_text(item) for item in value]
Alyssa Haroldsen
  • 3,652
  • 1
  • 20
  • 35
Ballack
  • 906
  • 6
  • 12
-1

If you have Python with this shape:

list_name = []
for item in other_list:
    list_name.append(function(item))

You can rewrite it as either of these:

list_name = [function(item) for item in other_list]
list_name = list(map(function, other_list))

There is one small difference: you assign to replaced_text, and that might be a variable outside the loop, and we don't know the rest of the code.

Alyssa Haroldsen
  • 3,652
  • 1
  • 20
  • 35
-1
if isinstance(value, list):
   new_value_list = [substitute_jirae_text(item) for item in value]

Understand how list comprehensions work. At first you'll need to write what do you want to append(certainly not creating any other variable). Then write the loop and then give the condition(if there are any). Also list comprehensions can't be used in every loop because sometimes it's way too confusing or there are restrictions (like assigning to a variable). Understand the concept yourself rather than let other doing it.

I-am-developer-9
  • 434
  • 1
  • 5
  • 13
-1
if isinstance(value, list):
    new_value_list = [substitute_jirae_text(item) for item in value]
    section_dict[key] = new_value_list
else: 

You can rewrite as above:

Alyssa Haroldsen
  • 3,652
  • 1
  • 20
  • 35
biba
  • 1
  • 4
  • 1
    Your answer could be improved with additional supporting information. Please [edit] to add further details, such as citations or documentation, so that others can confirm that your answer is correct. You can find more information on how to write good answers [in the help center](/help/how-to-answer). – Community Apr 01 '22 at 03:42