1nums = [4, -7, 9, 1, -1, 8, -6]
2half_of_nums = [x/2 for x in nums] #[2, -3.5, 4.5, 0.5, -0.5, 4, -3]
3
4#optionally you can add an if statement like this
5half_of_positive_nums = [x/2 for x in nums if x>=0] #[2, 4.5, 0.5, 4]
1#example: removing common elements found in `a` from `b`.
2a = [1,2,3,4,5]
3b = [5,6,7,8,9]
4# desired output: [1,2,3,4]
5
6# gets each item found in `a` AND not in `b`
7print([i for i in a if i not in b])
1lst=[1,2,3,4,5]
2lst2=[item for item in lst if <condition>]
3# generates a list based on another list and an if statement. the code above is a replacement for:
4lst=[1,2,3,4,5]
5lst2=[]
6for item in lst:
7 if <condition>:
8 lst2.append(item)
1# List comprehension example
2list = [0 for i in range(10)]
3# Makes a list of 10 zeros (Change 0 for different result
4# and range for different length)
5
6# Nested List
7list = [[0] * 5 for i in range(10)]
8# Makes a nested list of 10 list containing 5 zeros (You can also change
9# all of the int to produce different results)
1# PYTHON LIST COMPREHENSION
2#ordinary syntax:
3numbers = []
4for x in range(10):
5 numbers.append(x)
6print(numbers)
7
8#LIST COMPREHENSION syntax:
9numbers = [x for x in range(10)]
10print(numbers)
11
12#Both get the same result.
13
14#Check the official documentation:
15'''
16https://www.w3schools.com/python/python_lists_comprehension.asp
17'''
1 # A list comprehnsion is a for loop on a single line
2 # To create a list comprehension, swap the two lines in the for loop.
3
4# Here we use PyBIDS to extract the relative path for each file:
5for fmri in fmri_078:
6 print(fmri.relpath)
7
8# And here is the equivalent statement as a list comprehension.
9# It must be enclosed in square brackets.
10# It swaps the order of the lines and loses the colon and indentation
11[ print(fmri.relpath) for fmri in fmri_078 ]
1fruits = ["apple", "banana", "cherry", "kiwi", "mango"]
2newlist = []
3
4for x in fruits:
5 if "a" in x:
6 newlist.append(x)
7
8print(newlist)