Range len data python

Python – What is range(len())

In Python, len() function with an iterable as argument returns the number of elements in that iterable. And range(len()) returns a generator with a sequence of integers from 0 upto the length of the iterable.

This sequence of integers returned by the range() function can be used as indices of the elements in the iterable.

For example, consider the following list.

my_list = ['apple', 'banana', 'cherry']

len(my_list) returns a value 3, because there are three elements in the list. Easy.

Now, we pass the value returned by the len() function as argument to the range() function.

This creates a range object with a start value of 0 and stop value of 3, where 3 is the length of the given list. And the sequence of these integer values in the range object is given below.

If we can use a For loop to iterate over the range, we have access to the index of the element in the For loop, as shown in the following program.

Python Program

my_list = ['apple', 'banana', 'cherry'] for i in range(len(my_list)): print(my_list[i])

The same explanation holds for any ordered iterable, say tuple, string, etc.

In this tutorial of Python Ranges, we learned what range(len()) means, and how to use this expression to iterate over the indices of a given iterable.

Источник

4 полезных приема работы с Python

Прочитав эту статью, вы научитесь избегать ненужных циклов for , более эффективно получать доступ к элементам словаря и многому другому!

Один из плюсов Python — с его помощью можно заставить работать что угодно.

Еще один плюс — множество скрытых фишек, которые не только облегчают написание кода, но и делают код «чище» и удобнее для чтения.

В этой статье мы разберем фишки, которые помогут вам отточить ваши навыки.

1. Забудьте о range(len()). Наш выбор — enumerate()

Часто возникают ситуации, когда нужно перебрать коллекцию и отслеживать индексы элементов, к которым вы получили доступ. Для этих целей многие использует range(len(коллекция)) .

Функция enumerate возвращает enumerate-объект, который хранит в себе и индексы элементов, и их значения.

С помощью этой функции вы облегчите доступ и к индексам, и к значениям.

Рассмотрим пример, в котором видна разница между range(len(коллекция)) и enumerate(коллекция) .

# объявляем коллекцию — список: names = ['Никита', 'Дарья', 'Екатерина', 'Дмитрий', 'Владимир'] # в случае с range(len(collection)) вы бы написали: for i in range(len(names)): print(i, names[i]) # в случае с enumerate вы бы написали: for idx, name in enumerate(names): print(idx, name) # Оба варианта возвращают: # 0 Никита # 1 Дарья # 2 Екатерина # 3 Дмитрий # 4 Владимир

Еще одна полезная особенность enumerate — можно начинать отсчет не с 0. Для этого вам нужно лишь добавить параметр — start=параметр . Предположим, мы хотим начать выводить элементы списка с 1.

# объявляем коллекцию — список: names = ['Никита', 'Дарья', 'Екатерина', 'Дмитрий', 'Владимир'] # при использовании enumerate перебор с 1 реализуется так: for idx, name in enumerate(names, start=1): print(idx, name) # Цикл вернет: # 1 Никита # 2 Дарья # 3 Екатерина # 4 Дмитрий # 5 Владимир

2. Забудьте о квадратных скобках — получайте элементы словаря с помощью .get()

И хотим получить значение возраст . Возможно, вы уже привыкли использовать в таких случаях nikita[‘возраст’] . В нашем примере это сработает, но если значения не существует, — нет.

Например, при попытке получить доступ к несуществующему значению ‘место жительства’ мы получим ошибку KeyError :

nikita = < 'возраст':32, 'пол':'мужской', 'трудоустроен':True, >print(nikita['место жительства']) # Вывод: # KeyError: 'место жительства'

Если бы мы перебирали список словарей, эта ошибка могла бы прервать выполнение нашей программы. Да, конечно, мы бы могли использовать try, except — но зачем, если есть метод .get() ?

Если значения, к которому мы хотим получить доступ, не существует — возвращается None . Это очень удобно!

nikita = < 'возраст':32, 'пол':'мужской', 'трудоустроен':True, >print(nikita.get('место жительства')) # Вывод: # None

3. Облегчите перебор нескольких списков с помощью zip()

Порой возникают ситуации, когда у нас есть несколько коллекций (например, списков) и все их нужно перебрать.

В примере №1 мы разбирали способ с применением range(len(collection)) , но он не самый лучший.

names = ['Никита', 'Дарья', 'Екатерина', 'Дмитрий'] ages = [32, 28, 37, 53] gender = ['Мужчина', 'Женщина', 'Женщина', 'Мужчина'] # старый и скучный способ: for_looped = [] for i in range(len(names)): for_looped.append((names[i], ages[i], gender[i])) print(for_looped) # Вывод: # [('Никита', 32, 'Мужчина'), ('Дарья', 28, 'Женщина'), ('Екатерина', 37, 'Женщина'), ('Дмитрий', 53, 'Мужчина')]

Как видите, в результате мы получаем список, содержащий кортежи с элементами из каждого списка.

Этот способ, конечно, рабочий. Но если коллекций станет слишком много, код выйдет громоздким.

С помощью встроенной функции zip() мы можем все немного упростить.

Обратите внимание: функция zip() возвращает zip-объект , но с помощью приведения типов вы можете преобразовать его — например, с помощью list() , tuple() или dict() .

А теперь рассмотрим тот же пример и снова вернем список кортежей:

names = ['Никита', 'Дарья', 'Екатерина', 'Дмитрий'] ages = [32, 28, 37, 53] gender = ['Мужчина', 'Женщина', 'Женщина', 'Мужчина'] # перебор списков с помощью zip() zipped = zip(names, ages, gender) zipped_list = list(zipped) print(zipped_list) # Вывод: # [('Никита', 32, 'Мужчина'), ('Дарья', 28, 'Женщина'), ('Екатерина', 37, 'Женщина'), ('Дмитрий', 53, 'Мужчина')]

Выглядит намного лучше, не так ли?

Также вы можете преобразовывать коллекции в словари напрямую. Но обратите внимание — коллекций должно быть только две.

Например, вы хотите создать словарь, в котором пара ключ-значение — это имя:возраст . Сделать это можно так:

names = [‘Никита’, ‘Дарья’, ‘Екатерина’, ‘Дмитрий’] ages = [32, 28, 37, 53] gender = [‘Мужчина’, ‘Женщина’, ‘Женщина’, ‘Мужчина’] ages = dict(zip(names,ages)) print(ages) # Вывод: #

Если вы сделаете то же самое, но коллекций будет больше двух — появится исключение ValueError .

4. Используем f-строки для упрощения вывода информации в консоль

Начиная с Python 3.8 f-строки могут быть использованы для самодокументирования — с помощью = .

Это значит, что для того, чтобы вывести в консоль какое-то значение, вам больше не нужно писать f»variable_name = » .

some_variable = "ПРИВЕТ!" print(f"some_variable=") # Вывод: # some_variable=ПРИВЕТ!

Вместо этого вы можете написать:

some_variable = 'Привет!' print(f'') # Вывод: # some_variable='Привет!'

Изменение это небольшое, но довольно важное. Благодаря ему вы не просто избавитесь от повторений в коде, но и упростите его чтение.

Заключение

Возьмите все эти четыре совета на заметку : благодаря им ваш код будет стабильнее. Еще один плюс — ваш код будет выглядеть гораздо совершеннее и утонченнее.

Источник

Range len-1 in Python

Learn Algorithms and become a National Programmer

In this article, we have explained the Python code snippet «range(len(list)-1, -1, -1)» and other variants of the code snippet.

In short, the for loop in Python «for i in range(len(list)-1, -1, -1)» is used to loop through all elements of a list in reverse order that is from end to first.

for i in range(len(list)-1, -1, -1): # do something like learning at OpenGenus 

We will start with a basic for loop in Python and incrementally change the code to arrive to Range len-1 in Python.

Range len-1 in Python

  1. Range in Python
  2. range(len(list))
  3. range(len(list)-1)
  4. range(len(list)-1, 0, -1)
  5. range(len(list)-1, -1, -1)

Range in Python

Range is a built-in function in Python that is used to generate a list of numbers. The structure of range is as follows:

range(starting_index, last_index, increment) 
  • starting_index: This is optional and the default value is 0.
  • last_index: This is the value at which the iteration or list need to be stopped. This is a complusory parameter.
  • increment: This is the value by which the starting index is incremented at each step. This is optional and the default value is 1.

This generates a list of numbers starting with the number «starting_index», incrementing with value «increment» and ending before the number «last_index».

If range(2, 6, 1), then the sequence is:
2, 3, 4, 5

If range(9, 15, 2), then the sequence is:
9, 11, 13

range(len(list))

As only the ending index is complusory, then if one number is provided to range() then the starting number is set to 0 and increment is set to 1.

range(len(list)) is used to generate all sequence of indices in a list as the ending number is length of the list and the starting index is 0 so that last index is length-1.

Consider the following Python code snippet:

list = [10, 5, 99, -90, 12] for i in range(len(list)): print("Index ", i, ": ", list[i]) print() 

Following will be the output of the above Python code:

Index 0 : 10 Index 1 : 5 Index 2 : 99 Index 3 : -90 Index 4 : 12 

range(len(list)-1)

In this variant, we have updated len(list) to len(list)-1 that is we are eliminating the last element of the list.

Consider the following Python code snippet:

list = [10, 5, 99, -90, 12] for i in range(len(list)-1): print("Index ", i, ": ", list[i]) print() 

Following will be the output of the above Python code:

Index 0 : 10 Index 1 : 5 Index 2 : 99 Index 3 : -90 

Note the last element at index 4 which is 12 is not printed.

range(len(list)-1, 0, -1)

In this variant, we have provided all parameters. The starting index is the last index of the list and sequence will terminate when 0 is generated. The increment is -1 that is the sequence is decremented by 1 at each step.

This will generate the indices of the list in reverse order but not as the index starts from 0 and the sequence will end when 0 is generated, the first index of the list will not be generated.

Consider the following Python code snippet:

list = [10, 5, 99, -90, 12] for i in range(len(list)-1, 0, -1): print("Index ", i, ": ", list[i]) print() 

Following will be the output of the above Python code:

Index 4 : 12 Index 3 : -90 Index 2 : 99 Index 1 : 5 

Note the first element that is at index 0 which is 10 is not printed.

range(len(list)-1, -1, -1)

This is the final variant where there are multiple -1s. As explained by the syntax, the starting element is len(list)-1 that is the last index of the list.

-1 is the increment factor so this will decrement the values by 1 at each step.

The sequence will stop when -1 is generated so the last element will be 0 which is the first index of the list.

Hence, this will generate the list of indices of list in reverse order. This can be used to print a list in reverse order.

Consider the following Python code snippet:

list = [10, 5, 99, -90, 12] for i in range(len(list)-1, -1, -1): print("Index ", i, ": ", list[i]) print() 

Following will be the output of the above Python code:

Index 4 : 12 Index 3 : -90 Index 2 : 99 Index 1 : 5 Index 0 : 10 

Note that the elements of the list has been printed in reverse order.

With this article at OpenGenus, you must have the complete idea of range(len(list)-1, -1, -1) in Python.

Benjamin QoChuk, PhD

Benjamin QoChuk, PhD

Benjamin QoChuk is a Computer Science Researcher, Inventor and Author. His educational background include Bachelors at Vanderbilt University and PhD in Computer Science at Peking University.

OpenGenus Tech Review Team

Python

Python lambda if else

In this article, we have presented how to use if else elif as a part of Lambda function in Python. We have covered different cases like if, if else and if else elif with Python code examples.

Ned Nedialkov

Ned Nedialkov

[FIXED] TypeError: unsupported operand type(s) for +: ‘NoneType’ and ‘NoneType’

In this article, we have explained the reason behind the Python runtime error «TypeError: unsupported operand type(s) for +: ‘NoneType’ and ‘NoneType'» and presented two ways to fix the error.

Ned Nedialkov

Ned Nedialkov

Источник

Читайте также:  Php dateperiod to array
Оцените статью