Search
 
SCRIPT & CODE EXAMPLE
 

PYTHON

Creating a list with list comprehensions

# construct a basic list using range() and list comprehensions
# syntax
# [ expression for item in list ]
digits = [x for x in range(10)]

print(digits)
Comment

List Comprehension generate a list

# generate a list
li = [ i+1 for i in [1,2,3] ]
print(li)
# [2, 3, 4]
Comment

Writing a List Comprehension

# Define a generic 1D list of constants
my_list = [2, 5, -4, 6]

# Duplicate a 1D list of constants
[item for item in my_list]

# Duplicate and scale a 1D list of constants
[2 * item for item in my_list]

# Duplicate and filter out non-negatives from 1D list of constants
[item for item in my_list if item < 0]

# Duplicate, filter, and scale a 1D list of constants
[2 * item for item in my_list if item < 0]

# Generate all possible pairs from two lists
[(a, b) for a in (1, 3, 5) for b in (2, 4, 6)]

# Redefine list of contents to be 2D
my_list = [[1, 2], [3, 4]]

# Duplicate a 2D list
[[item for item in sub_list] for sub_list in my_list]

# Duplicate an n-dimensional list
def deep_copy(to_copy): 
  if type(to_copy) is list: 
    return [deep_copy(item) for item in to_copy] 
  else: 
    return to_copy
Comment

PREVIOUS NEXT
Code Example
Python :: extract column numpy array python 
Python :: how to reference a file in python 
Python :: pip clear download cache 
Python :: how to convert img to gray python 
Python :: enumerate python 
Python :: how to read a text file from url in python 
Python :: how to do http requetss python 
Python :: python get path of current file 
Python :: ipywidegtes dropdown 
Python :: python textbox 
Python :: torchvision.transforms 
Python :: taking multiple input in python 
Python :: how to remove the last item in a list python 
Python :: merge on row number python 
Python :: python convert list of strings to list of integers 
Python :: add hour minutes second python 
Python :: find the first occurrence of item in a list in python 
Python :: python multiply list 
Python :: sklearn train_test_split 
Python :: how to commenbt code in python 
Python :: python put quotes in string 
Python :: natural log and log base 10 in python 
Python :: get int64 column pandas 
Python :: remove all integers from list python 
Python :: python randomly chose user agent 
Python :: python make directory tree from path 
Python :: case insensitive replace python 
Python :: should i make tkinter in classes ? , Best way to structure a tkinter application? 
Python :: pygame caption 
Python :: pandas reset index without adding column 
ADD CONTENT
Topic
Content
Source link
Name
8+4 =