Intermediate Python 4. List Comp & Generators 영어 파이썬 코딩영어
LC training(0:18) - One of the most common generators that you've probably been using is range So when you say for i in range of five this does not generate a list of 0 1 2 3 4 it's a generator and it generates a stream in the range of 0 to 5 which is producing 0 1 2 3 4 so But it doesn't do that and save it all into memory as apposed to say list comprehension or a list that actually obviously would store that into memory So in Python 2 range actually isn't a generator and it does store that entire list in the memory which is why if you in Python 3 you can get away with saying like i equals range this that's okay You're going to be just fine when you do that right We can do that real quick ok boom it's already done all right But in Python 2 if you run that code it's gonna be like plurr ~ like it's just not gonna happen and you're gonna have to close out a Python okay so Because it's generating a list and it's just going to blow your memory so generator Now fundamentally we'll i have to keep hitting this point as we go through this entire course really But list comprehension or a list is going to be faster but it's going to use your memory right It's going to use your RAM to store that list and that's why it's faster It's already loaded boom it's in memory Generators on the other hand are going to be slower but they're not going to use as much memory and slower is like with an asterisk Because building a list actually like when it comes time to build and save that list to a variable that can actually sometimes be a pretty time intensive process so Actually sometimes generators are faster But in most like raw cases the generator is going to be slower it's just not going to blow out your memory
Summary & Code results -
range function은 python 2에선 not a generator 였다. it does store the entire list in memory. as the result when it's big number, it will blowout your memory. 그러다 이제 python 3에 와선 generator가 되었고, it doesn't store in the memory. range(5)라 하면, it generates a stream in the range of 0 to five, produces 0, 1, 2, 3, 4, builds and saves that list to a variable.
list comprehension은 xyz = [i for i in range(5)], generator expression은 xyz = (i for i in range(i)) 라고 코딩한다. 전자는
xyz = []
for i in range(5):
xyz.append(i)
후자는
for i in xyz:
print(i)
해보면 둘이 동일하게 [0, 1, 2, 3, 4] 를 출력해는 걸 볼 수 있다. 이 둘은 전자는 메모리를 잡아먹고, 후자는 프로세스 타임을 잡아 먹는다는 특성을 갖고 있다. 아래와 같이 몇 차례 number를 바꿔가며 실습을 통해 그 현상을 지켜볼 수 있었다.
xyz = [i for i in range(50000000)] # list comprehension - loads in a list memory
print('done') # ... it took 3.8 secs
xyz = (i for i in range(50000000)) # generator expression - creates an object
print(xyz) # ... it took only 0.1 secs
--------------------------------------------------------------------------
done
generator object genexpr at 0x000001E91BACBAC0
[Finished in 3.9s]
원본 비디오: https://www.youtube.com/watch?v=ZoWgzG_r2qo&list=PLQVvvaa0QuDfju7ADVp5W1GF9jVhjbX-_&index=5
Что делает видео по-настоящему запоминающимся? Наверное, та самая атмосфера, которая заставляет забыть о времени. Когда вы заходите на RUVIDEO, чтобы посмотреть онлайн «Intermediate Python 4. List Comp & Generators 영어 파이썬 코딩영어», вы рассчитываете на нечто большее, чем просто загрузку плеера. И мы это понимаем. Контент такого уровня заслуживает того, чтобы его смотрели в HD 1080, без дрожания картинки и бесконечного буферизации.
Честно говоря, Rutube сегодня — это кладезь уникальных находок, которые часто теряются в общем шуме. Мы же вытаскиваем на поверхность самое интересное. Будь то динамичный экшн, глубокий разбор темы от любимого автора или просто уютное видео для настроения — всё это доступно здесь бесплатно и без лишних формальностей. Никаких «заполните анкету, чтобы продолжить». Только вы, ваш экран и качественный поток.
Если вас зацепило это видео, не забудьте взглянуть на похожие материалы в блоке справа. Мы откалибровали наши алгоритмы так, чтобы они подбирали контент не просто «по тегам», а по настроению и смыслу. Ведь в конечном итоге, онлайн-кинотеатр — это не склад файлов, а место, где каждый вечер можно найти свою историю. Приятного вам отдыха на RUVIDEO!
Видео взято из открытых источников Rutube. Если вы правообладатель, обратитесь к первоисточнику.