Python Tutorials - List Comprehension

Published: 29 December 2018
on channel: Lets Code
21
0

Info:
-------
For the complete course details, projects and questions, please reach here:

Email: letscodeinst@gmail.com
Profile: https://sterling.universitytutor.com/...


Code - List Comprehension:
--------------------------------------------
#!/usr/bin/python

Constructing a list of numbers from 1 - 10
numberList = []
for i in range(1, 11):
numberList.append(i)

print ("List of numbers: ")
print (numberList)


numberListComprehension = [i for i in range(1,11)]
print (numberListComprehension)

Constructing a list of even numbers from 2 - 10
evenNumbersList = []
for i in range(1, 11):
if i % 2 == 0:
evenNumbersList.append(i)
print ("Even numbers through regular method: ")
print (evenNumbersList)

evenNumbersListComprehension = [i for i in range(1,11) if i%2 == 0]
print (evenNumbersListComprehension)


Constructing a list of odd numbers from 1 - 9
oddNumbersList = []
for i in range(1,11):
if i % 2 != 0:
oddNumbersList.append(i)
print ("Odd numbers through regular method: ")
print (oddNumbersList)

oddNumbersListComprehension = [i for i in range(1,11) if i%2 != 0]
print (oddNumbersListComprehension)


Constructing a list of tuples
classInfoList = []
studentNames = ['John', 'Mary', 'Nathan', 'Adam', 'Bob']
studentAges = [10, 9, 10, 11, 8]

for i in range(0, 5):
studentInfo = (studentNames[i], studentAges[i])
classInfoList.append(studentInfo)

print ("List of tuples: ")
print (classInfoList)

classInfoListComprehension = [(studentNames[i], studentAges[i]) for i in range(0,5)]
print (classInfoListComprehension)



Slide - List Comprehension:
--------------------------------------------

Concise way to create lists
Returns a list and can be:
List of singleton elements
List of tuples
List of dictionaries and so on
Syntax:
Square brackets
One or more FOR clause
One or more expressions to evaluate
Variables to be added to the list


On this page of the site you can watch the video online Python Tutorials - List Comprehension with a duration of hours minute second in good quality, which was uploaded by the user Lets Code 29 December 2018, share the link with friends and acquaintances, this video has already been watched 21 times on youtube and it was liked by 0 viewers. Enjoy your viewing!