Arrays in Python - ProgrammerTech
Language:

Search

Arrays in Python

  • Share this:
Arrays in Python

Arrays in Python

Arrays are a group of elements of the same type that are common in most programming languages, but in Python they are not very common, and in any programming language it is very important to be able to deal with a lot of information or the so-called big data And there is a lot of information or data that we are supposed to deal with, extract it and how to dispose of it.

There are 4 types of arrays in Python:

  1. Lists.
  2. Tuples.
  3. Dictionaries.
  4. Sets.

 

Lists in Python

Lists are an important type of data in Python and to use them we must have a set of elements that we store in six such as texts and numbers, and to create six we use square brackets [] and it is an adjustable order, that is, it is like the list of food in restaurants and it has items.

Example 1

>>> mylist = ["Muhammad", "kaissar", "saja"]
>>> mylist
['Muhammad', 'kaissar', 'saja']
>>> mylist2 = [1,2,3,4,5]
>>> mylist2
[1, 2, 3, 4, 5]
>>> mylist3 = [1, 2, 3, 4, 5, "wazeer"]
>>> mylist3
[1, 2, 3, 4, 5, 'wazeer']

As we note in the example, we can create six with text data as in mylist and six with numeric data as in mylist2 and six mixed text and numbers as in mylist3. Each element of the array is numbered with a number called index starting at 0.

Example 2

>>> mylist = [1,2,65,9,5]
>>> mylist[3]
9
>>> mylist[0:3]
[1, 2, 65]
>>> mylist[-1]
5
>>> len(mylist)
5
>>> max (mylist)
65
>>> min(mylist)
1
>>> list("1,2,3,4,5,6,7")
['1', ',', '2', ',', '3', ',', '4', ',', '5', ',', '6', ',', '7']
>>> list("kaissar")
['k', 'a', 'i', 's', 's', 'a', 'r']

We notice in the beginning we created a list called mylist and put some values ​​in it and then wrote mylist[3] and this means give us index No. 3 of this array and since the index starts counting from zero, the third index is 9. Then in the next line we wrote mylist [0:3] i.e. we give the set of indices from zero to three and the meaning of mylist [-1] i.e. we give the last indices, start counting from the last and the meaning of len i.e. we give the length of this list and max means knowing the largest number in this list and min to find out the smallest No. in this list.

And in the end, we gave it a set of numbers and we told the Python shell to convert it to a list, and then we gave it a text as well, and we turned it into a list.

Example 3

>>> mylist = [1,2,3,5,7,6]
>>> mylist [2] = 4
>>> mylist
[1, 2, 4, 5, 7, 6]
>>> mylist.append (7)
>>> mylist
[1, 2, 4, 5, 7, 6, 7]
>>> mylist.count (2)
1
>>> mylist.append (2)
>>> mylist.append (2)
>>> mylist
[1, 2, 4, 5, 7, 6, 7, 2, 2]
>>> mylist.count (2)
3
>>> mylist.index (4)
2
>>> mylist.insert (0,2)
>>> mylist
[2, 1, 2, 4, 5, 7, 6, 7, 2, 2]

We created six and they have several elements, then we started carrying out several operations on them, and the operations are:

  • The first operation we wrote mylist [2] = 4, which means replace the index number 2, which is 3, replace it with the number 4.
  • The second process we wrote mylist.append(7) and this means add the number 7 to this list and it will be added at the end.
  • The third process we wrote mylist.count (2) which means how many number 2 in this list and return us 1 i.e. there are two of one.
  • The third and fourth operation we wrote mylist.append(2) We wrote it twice, that is, add the number 2 twice in this list.
  • The fifth process We inquired how many number 2 in this group and returned 3 and of course there is number 2 three times.
  • The sixth operation mylist.index(4) i.e. what is the index of the number 4 in this list and return to us 2, meaning that the number 4 is ranked 2 in the list.
  • The seventh operation mylist.insert(0,2) ie add the number 2 in the first index whose order is 0.

Example 4

>>> mylist = [5,6,9,1,2,8,8,9,2]
>>> mylist.pop()
2
>>> mylist.remove(8)
>>> mylist
[5, 6, 9, 1, 2, 8, 9]
>>> mylist2 = [1,2,3,4,6,7,5,8]
>>> mylist2.sort()
>>> mylist2
[1, 2, 3, 4, 5, 6, 7, 8]
  • The pop() function randomly deletes from the array values ​​while printing the deleted value.
  • The function remove() removes a specified from within the array.
  • The function sort() is in alphabetical order if it is text and ascending order if it is numbers.

 

Tuples in Python

A tuple is not very different from Lists, but it is stronger than it with some needs, and it is an array of fixed size and in which values ​​of different types can be stored at the same time, but tuples cannot add or change an element and the matter is restricted and its brackets are circular ( ) is ordered and not adjustable.

How to create a tuple as follows

>>> x = ("muhammad" , "kaissar" , "saja")
print (x)
#output ('muhammad', 'kaissar', 'saja')

Example 1

x = tuple ("123456")
('1', '2', '3', '4', '5', '6')

We created a tuple and placed in it a set of numbers that we defined as texts that we placed between quotes, and when we use the print command for this example, the output will be as follows

>>> print (x)
('1', '2', '3', '4', '5', '6')

As we noticed when using the print command, the numbers in this tuple were printed for us, each number separately, inside quotation marks.

 

Use the count command to find similar items

Example 2

>>> t = ("a","b","c","a")

In this example, we created a variable t and put some English letters in it, and when we use the count command and ask for the letter a, the result will be in the form

>>> t.count ("a")

When you press the Enter button, it will print the number 2, meaning that there are two letters a in this example.

 

Find out the position of the index element

>>> t = ("a","b","c","a")

We created a variable which is t and put some English letters in it, and when using the index command and asking it to find out the position of the letter b, the result will be in the form

>>> t.index("b")

When we press the Enter button, it will print the number 1, which is the position of the letter b in this array.

 

Slicing in a tuple

>>> t = ("a","b","c","a")

To cut a part of a text string in a tuple, we use a colon and write the starting and ending index, we will cut from 0 to 2 of this string and it will be in the form.

>>> t [0:2]

When we press the Enter button to execute the command, the result will be as

('a', 'b')

If we write the command to modify a value from this string

t[0] = "d"

It will give us an error like this:

Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: 'tuple' object does not support item assignment

It gave us the error because one of the tuple laws is that they are not modifiable.

 

dictionaries in Python

The class dict uses curly braces {} and consists of a key and its value, like in Arabic dictionaries the word and its meaning. It is unordered and its content is changeble.

General form of dictionaries in Python

x = {key : value , key2 : value2}

Example 1

>>> info = {'name':'data', 'age':26}
>>> info ["name"]
'data'
>>> info ["age"]
26

At first we defined the info variable and gave it values ​​and keys to get a dictionary, and then we asked the key data for the first value which is name and gave us the value which is data, then we asked the program to print the dictionary values ​​and print them for us 26.

 

print values ​​in class dict

In order to print only the values ​​from the dict array in Python we use the .values ​​command after the name of the variable that holds the dictionary.

>>> info = {'name':'data', 'age':26}
>>> info.values()

We have created an info dictionary and there are two values ​​in this dictionary and we want to print them via the info.values() command and this command when we press the Enter button will be the result.

dict_values(['data', 26])

As we noted, only the values ​​in this dictionary have been printed.

 

Typing keys in class dict

In order to print only the keys from the dict array in Python we use the .keys() command after the name of the variable that holds the dictionary.

>>> info = {'name':'data', 'age':26}
>>> info.keys()

We created the info dictionary and there are two keys in this dictionary and we want to print them via the info.keys() command and this command when we press the Enter button will be the result.

dict_keys(['name', 'age'])

 

Functions of a dict object in Python

>>> info = {'name':'data' , 'age':27}
>>> info.clear()
>>> info
{}
>>> ahmed = {'name':'kaissar' , 'age':22}
>>> saja = ahmed.copy()
>>> saja
{'name': 'kaissar', 'age': 22}
>>> saja.fromkeys("j")
{'j': None}
>>> d2 = {"name" : "kaissar" , "age":22}
>>> d2.get("age")
22
>>> ("age" in d2)
True
>>> d2.setdefault("d","a")
'a'
>>> d2
{'name': 'kaissar', 'age': 22, 'd': 'a'}
>>> d2.items()
dict_items([('name', 'kaissar'), ('age', 22), ('d', 'a')])
  1. The clear() function deletes the contents of the dictionary, i.e. deletes all items.
  2. The copy() function copies the contents of the kaissar dictionary to a new dictionary named saja.
  3. The fromkeys() function creates a new dictionary from the parameters specified by the user. The j dictionary is created with an empty value.
  4. The get() function gives us the value specified in the dictionary and gives us the value of age we specified.
  5. The setdefault() function returns the value of the specified key, and if it does not exist, it creates a dictionary of value and key, and here it creates the key d and the value a.
  6. The items() function returns the display of the dictionary, the key and the value of each one in square brackets separately.

 

set class in python

The set is an array that does not have a fixed size, but rather a variable, and it can store values ​​of different types at one time, i.e. numbers, texts, decimal data, etc., and its values ​​cannot be directly altered or deleted, and it cannot contain On duplicate values, that is, if you put the same value twice in it, one value will be stored, not two values.

The set is considered unordered, meaning random, and does not have an index. It is frequently used to create or generate six strong passwords. It is changable. The curly braces {} are used with the dict class. Inside these parentheses you can pass the values ​​directly provided you put a comma between All two components.

Example 1

>>>num = {1, 2, 3, 5, 6, 8, 9}

We created six set which are num and put only a set of integers in them, and when we write the print command for this command it will be.

>>> print(num)

And we will get the result

{1, 2, 3, 5, 6, 8, 9}

Example 2

>>>names = {'Muhammad', 'Ahmed', 'Saja'}

We created six set which are names and put a set of text data only in them, and when we write the print command for this command it will be.

>>> print(names)

And we will get the result

{'Muhammad', 'Ahmed', 'Saja'}

 

Adding a new element to the set

>>> names = {'Muhammad', 'Ahmed', 'Saja'}

To add a value to this array we use the add() function, we will add a new value to this array in the form

>>> names.add("muhammal")

When we execute this code via the command

>>> print(names)

It will add value to us randomly

{'muhammal', 'Ahmed', 'Muhammad', 'Saja'}

As we have noted, he has randomly added the new value in this set.


Tags:
Muhammad Alush

Muhammad Alush

إسمي محمد تركي العلوش من سورية من ريف حلب الشرقي 1994, محب للتقنية و التعلم الذاتي, و جميع خبراتي تعلمتها ذاتياً, و اللغات البرمجية التي أتقنها هي html, css, javascript, php, c, python بالإضافة إلى حبي الكبير لمجال الشبكات.

موقعي programmer-tech.com