Python Bytes: List Comprehensions Introduction

Published: 14 May 2021
on channel: CyberScribe.org
34
1

Python Bytes
Intermediate Python Topics
List Comprehensions Introduction

#A method of making lists from other values.

#Defining a list and its contents at the same time.

new_list = [ item for item in iterable ]

#An 'iterable' is an object that contains other objects within it.
#Lists, Dictionaries, Tuples, Sets, range(), and more.

#You can work backwards from a loop to create the comprehension and understand the logic.
#This is a good technique when you are still new to list comprehensions.

#Example 1:
new_list = list()
for num in range(0,10):
new_list.append(num)

new_list = [num for num in range(0,10)]


#Example 2:
fqdns = ['abc.dev.com', 'dew.qka.com', 'kwlan.ewa.com']
hostnames = list()
for fqdn in fqdns:
hostnames.append(fqdn.split('.')[0])

hostnames2 = [ fqdn.split('.')[0] for fqdn in fqdns ]


Watch video Python Bytes: List Comprehensions Introduction online without registration, duration hours minute second in high quality. This video was added by user CyberScribe.org 14 May 2021, don't forget to share it with your friends and acquaintances, it has been viewed on our site 3 once and liked it people.