Как заполнить массив числами python
Перейти к содержимому

Как заполнить массив числами python

  • автор:

Learn How To Use Arrays In Python With Example

Edureka

In the immensely fast moving world, one needs resourceful coding techniques that could help the programmer to sum up voluminous codes in the simplest and most convenient ways. Arrays are one of the data structures that help you write a number of values into a single variable, thereby reducing the burden of memorizing an enormous number of variables. So let’s go ahead, and see how you can implement Arrays in Python.

Here’s an overview of the topics which explains all the aspects dealing with arrays:

  1. Why use Arrays in Python?
  2. What is an Array?
  3. Is Python list same as an Array?
  4. Creating an Array
  5. Accessing an Element
  6. Basic Array Operations
  • Adding/ Changing elements of an Array
  • Concatenation
  • Deleting / Removing elements from an Array
  • Looping through an array
  • Slicing

Why use Arrays in Python?

A combination of Arrays, together with Python could save you a lot of time. As mentioned earlier, arrays help you reduce the overall size of your code, while Python helps you get rid of problematic syntax, unlike other languages. For example: If you had to store integers from 1–100, you won’t be able to remember 100 variable names explicitly, therefore, you can save them easily using an array.

Now that you are aware of the importance of arrays in Python, let’s study more about it in detail.

What is an Array?

An array is basically a data structure which can hold more than one value at a time. It is a collection or ordered series of elements of the same type.

We can loop through the array items easily and fetch the required values by just specifying the index number. Arrays are mutable(changeable) as well, therefore, you can perform various manipulations as required.

Now, there is always a question that comes up to our mind —

Is Python list same as an Array?

The ‘array’ data structure in core python is not very efficient or reliable. Therefore, when we talk about python arrays, we usually mean python lists.

However, python does provide Numpy Arrays which are a grid of values used in Data Science.

Creating an Array:

Arrays in Python can be created after importing the array module as follows —

→ import array as arr

The array(data type, value list) function takes two parameters, the first being the data type of the value to be stored and the second is the value list. The data type can be anything such as int, float, double, etc. Please make a note that arr is the alias name and is for ease of use. You can import without alias as well. There is another way to import the array module which is —

→ from array import *

This means you want to import all functions from the array module.

The following syntax is used to create an array.

Syntax:

Example: a=arr.array( ‘d’ , [1.1 , 2.1 ,3.1] )

Here, the first parameter is ‘d’ which is a data type i.e. float and the values are specified as the next parameter.

Note: All values specified are of the type float. We cannot specify the values of different data types to a single array.

The following table shows you the various data types and their codes.

Accessing array elements :

To access array elements, you need to specify the index values. Indexing starts at 0 and not from 1. Hence, the index number is always 1 less than the length of the array.

Syntax:

Output:

The output returned is the value, present in the second place in our array which is 2.1.

Let us have a look at some of the basic array operations now.

Basic array operations :

There are many operations that can be performed on arrays which are as follows —

Finding the Length of an Array

Length of an array is the number of elements that are actually present in an array. You can make use of len() function to achieve this. The len() function returns an integer value that is equal to the number of elements present in that array.

Syntax:

Example:

Output:

This returns a value of 3 which is equal to the number of array elements.

Adding/ Changing elements of an Array:

We can add value to an array by using the append(), extend() and the insert (i,x) functions.

The append() function is used when we need to add a single element at the end of the array.

Example:

Output

The resultant array is the actual array with the new value added at the end of it. To add more than one element, you can use the extend() function. This function takes a list of elements as its parameter. The contents of this list are the elements to be added to the array.

Example:

Output

The resulting array will contain all the 3 new elements added to the end of the array.

However, when you need to add a specific element at a particular position in the array, the insert(i,x) function can be used. This function inserts the element at the respective index in the array. It takes 2 parameters where the first parameter is the index where the element needs to be inserted and the second is the value.

Example:

Output

The resulting array contains the value 3.8 at the 3rd position in the array.

Arrays can be merged as well by performing array concatenation.

Array Concatenation :

Any two arrays can be concatenated using the + symbol.

Example:

Output —

The resulting array c contains concatenated elements of arrays a and b.

Now, let us see how you can remove or delete items from an array.

Removing/ Deleting elements of an array:

Array elements can be removed using pop() or remove() method. The difference between these two functions is that the former returns the deleted value whereas the latter does not.

The pop() function takes either no parameter or the index value as its parameter. When no parameter is given, this function pops() the last element and returns it. When you explicitly supply the index value, the pop() function pops the required elements and returns it.

Example:

Output —

The first pop() function removes the last value 4.6 and returns the same while the second one pops the value at the 4th position which is 3.1 and returns the same.

The remove() function, on the other hand, is used to remove the value where we do not need the removed value to be returned. This function takes the element value itself as the parameter. If you give the index value in the parameter slot, it will throw an error.

Example:

Output —

The output is an array containing all elements except 1.1.

When you want a specific range of values from an array, you can slice the array to return the same, as follows.

Slicing an array :

An array can be sliced using the : symbol. This returns a range of elements that we have specified by the index numbers.

Example:

Output

The result will be elements present at 1st, 2nd and 3rd position in the array.

Looping through an array:

Using the for loop, we can loop through an array.

Example:

Output

The above output shows the result using for loop. When we use for loop without any specific parameters, the result contains all the elements of the array given one at a time. In the second for loop, the result contains only the elements that are specified using the index values. Please note that the result does not contain the value at index number 3.

Hope you are clear with all that has been shared with you in this tutorial. This brings us to the end of our article on Arrays in Python. Make sure you practice as much as possible and revert your experience.

If you wish to check out more articles on the market’s most trending technologies like Artificial Intelligence, DevOps, Ethical Hacking, then you can refer to Edureka’s official site.

Do look out for other articles in this series which will explain the various other aspects of Python and Data Science.

How to create an array of numbers 1 to n in python

An array is a collection of items of same type stored at contiguous memory locations. To access the elements, you only need to know the memory address of the first item of an array which is also known as base address. You can access all other items or traverse in an array by simply adding an offset to this base address. Python lists can also be treated as arrays but the lists can store multiple data items of different datatypes. This article is about how to create an array of numbers 1 to N in Python. If you want to learn more about Python Programming, Visit Python Programming Tutorials.

  • CREATION OF AN ARRAY OF NUMBERS 1 TO N USING A RANGE() FUNCTION IN PYTHON.
  • CREATE AN ARRAY USING THE USER-DEFINED FUNCTION
  • CREATING AN ARRAY USING A NUMPY-ARANGE() FUNCTION
  • CREATE AN ARRAY USING PYTHON MODULE ARRAY

In the first three methods, we’ll see how lists can be treated as arrays. Python has a module called array which is used to work only with specific data values. The last method discusses how to create an array using this module. Lets discuss all these methods in detail.

CREATING AN ARRAY USING THE RANGE() FUNCTION

As discussed previously, python lists can be treated as arrays. To create an array of a certain range we can use the range() function as it specifies the range of the list and then typecast the range() by using the list command as shown in the code below. We can set the range of the list from 1 to N and N should be any integer number.

CODE:

creating an array by a user-defined function

Another way is to create a function and pass the length of an array as a parameter to this function. In the example below, we have created a function by the name of List-Function. The function takes parameter ‘n’ which represents the length of the array. In this function, a for loop is used which treats n as the last index of the array and append the number in the List_array starting from 0 up to the maximum length ‘n’ as shown below.

CODE:

cREATING AN ARRAY USING nUMPY.ARANGE() FUNCTION

The numpy library provides an arrange() function which takes two parameters as an integers and generate the numbers starting from the first parameter upto the last parameter. Typecast the arange() function using the list command and an array is created.

numpy.arange() is used to create an array of large sizes.

CREATE AN ARRAY USING PYTHON MODULE ARRAY

An array module of python is used to create an array consisting of elements or items of same datatypes. The array module takes two arguments as an input. The first one is datatype of an array such as ‘i’ for integer. All other datatypes are given in the this link. The second argument consists of the elements or items of an array.

In the example above, we have created two arrays arr1 and arr2 of integers and floating numbers. The function display here is used to print the contents of an array created. It takes two arguments: an array ‘n’ and the size of array ‘s’ created.

There are different operations that can be carried out on arrays such as insertion, deletion, sorting arrays into ascending and descending order etc. Try them on your own. If you have any query regarding this topic or any other topic related to python programming language, let us know in the comments or contact us.

Заполнение списка рандомными значениями в Python

Статьи

Введение

В этой небольшой статье рассмотрим способы заполнения списка рандомными значениями.

В основном будем использовать функции модуля random.

Заполнение списка используя функции модуля random

Заполнение списка используя функцию randint()

Самая распространённая функция в модуле random это конечно же randint(), и именно им мы воспользуемся в первом способе!

Для начала мы его импортируем, после чего создаём пустой список, который в последствии будем заполнять:

Далее нам понадобится цикл, в котором мы будем заполнять список рандомными значениями:

Осталось только вывести результат:

При желании можно значительно сократить код, и сделать генератор списка:

Заполнение списка используя функцию sample()

Самой подходящей функцией является как раз таки sample(), но почему-то о ней говорят редко.

Для начала естественно импортируем модуль random, после чего сгенерируем список рандомных значений и выведем их:

В функции range() мы указали диапазон чисел, а через запятую количество генерируемых чисел.

Заполнение списка используя функции модуля numpy

Переходим к генерации рандомных чисел с помощью модуля numpy. Из него мы будем использовать функцию randint().

Для начала мы его конечно же импортируем:

Далее создаём список, который мы сразу же заполняем рандомными значениями и выведем его:

В первом параметре мы указываем минимальное значение, которое может быть сгенерировано, во втором – максимальное, и в третьем количество значений.

Заключение

В статье мы с Вами научились генерировать списки с рандомными значениями разными способами. Надеюсь Вам понравилась статья, удачи! ��

Заполнить массив значением в NumPy

Заполнить массив значением в NumPy

Из этого туториала Вы узнаете, как заполнить массив значениями в NumPy.

Заполните массив значением с помощью функции numpy.full()

Функция numpy.full() заполняет массив заданной формой и типом данных определенным значением. Он принимает форму массива, значение для заполнения и тип данных массива в качестве входных параметров и возвращает массив с указанной формой и типом данных, заполненный указанным значением. См. Следующий пример кода.

В приведенном выше коде мы заполнили значение 7 внутри массива длиной 5 с помощью функции np.full() . Мы инициализировали массив NumPy идентичными значениями, указав форму массива и желаемое значение внутри функции np.full() .

Заполнить массив значением с помощью функции numpy.fill()

Мы также можем использовать функцию numpy.fill() для заполнения уже существующего массива NumPy аналогичными значениями. Функция numpy.fill() принимает значение и тип данных в качестве входных параметров и заполняет массив указанным значением.

Сначала мы создали массив NumPy array с помощью функции np.empty() . Он создает массив, содержащий только 0 в качестве элементов. Затем мы заполнили массив значением 7 с помощью функции array.fill(7) .

Заполнить массив значением с помощью цикла for в Python

Мы также можем использовать цикл for для присвоения отдельного значения каждому элементу массива в Python. Сначала мы можем создать массив с помощью функции numpy.empty() , указав форму массива в качестве входного параметра функции numpy.empty() . Затем мы можем присвоить желаемое значение каждому индексу массива, используя цикл for для итерации по каждому элементу массива.

Сначала мы создали массив NumPy array , указав форму массива в качестве входного параметра внутри функции numpy.empty() . Как обсуждалось в предыдущем примере, это создает массив указанной формы и заполняет каждый элемент массива значением 0 . Затем мы использовали цикл for для перебора каждого индекса array и явно указали, что каждое значение равно 7 .

Maisam is a highly skilled and motivated Data Scientist. He has over 4 years of experience with Python programming language. He loves solving complex problems and sharing his results on the internet.

Добавить комментарий

Ваш адрес email не будет опубликован. Обязательные поля помечены *