Jessica  Jacobs

Jessica Jacobs

1627017120

JavaScript Lecture - 33 Sort Array Method

Hello Friends,
In this lecture we are going to learn sort array method in javascript. If you like this lecture please don’t forget to share and subscribe for more lectures.

#sortarraymethod #arraysortmethod #javascript #javascriptarraymethod
#webdesign #softwaredevelopment #webdevelopment

#javascript

What is GEEK

Buddha Community

JavaScript Lecture - 33 Sort Array Method

How to Create Arrays in Python

In this tutorial, you'll know the basics of how to create arrays in Python using the array module. Learn how to use Python arrays. You'll see how to define them and the different methods commonly used for performing operations on them.

This tutorialvideo on 'Arrays in Python' will help you establish a strong hold on all the fundamentals in python programming language. Below are the topics covered in this video:  
1:15 What is an array?
2:53 Is python list same as an array?
3:48  How to create arrays in python?
7:19 Accessing array elements
9:59 Basic array operations
        - 10:33  Finding the length of an array
        - 11:44  Adding Elements
        - 15:06  Removing elements
        - 18:32  Array concatenation
       - 20:59  Slicing
       - 23:26  Looping  


Python Array Tutorial – Define, Index, Methods

In this article, you'll learn how to use Python arrays. You'll see how to define them and the different methods commonly used for performing operations on them.

The artcile covers arrays that you create by importing the array module. We won't cover NumPy arrays here.

Table of Contents

  1. Introduction to Arrays
    1. The differences between Lists and Arrays
    2. When to use arrays
  2. How to use arrays
    1. Define arrays
    2. Find the length of arrays
    3. Array indexing
    4. Search through arrays
    5. Loop through arrays
    6. Slice an array
  3. Array methods for performing operations
    1. Change an existing value
    2. Add a new value
    3. Remove a value
  4. Conclusion

Let's get started!

What are Python Arrays?

Arrays are a fundamental data structure, and an important part of most programming languages. In Python, they are containers which are able to store more than one item at the same time.

Specifically, they are an ordered collection of elements with every value being of the same data type. That is the most important thing to remember about Python arrays - the fact that they can only hold a sequence of multiple items that are of the same type.

What's the Difference between Python Lists and Python Arrays?

Lists are one of the most common data structures in Python, and a core part of the language.

Lists and arrays behave similarly.

Just like arrays, lists are an ordered sequence of elements.

They are also mutable and not fixed in size, which means they can grow and shrink throughout the life of the program. Items can be added and removed, making them very flexible to work with.

However, lists and arrays are not the same thing.

Lists store items that are of various data types. This means that a list can contain integers, floating point numbers, strings, or any other Python data type, at the same time. That is not the case with arrays.

As mentioned in the section above, arrays store only items that are of the same single data type. There are arrays that contain only integers, or only floating point numbers, or only any other Python data type you want to use.

When to Use Python Arrays

Lists are built into the Python programming language, whereas arrays aren't. Arrays are not a built-in data structure, and therefore need to be imported via the array module in order to be used.

Arrays of the array module are a thin wrapper over C arrays, and are useful when you want to work with homogeneous data.

They are also more compact and take up less memory and space which makes them more size efficient compared to lists.

If you want to perform mathematical calculations, then you should use NumPy arrays by importing the NumPy package. Besides that, you should just use Python arrays when you really need to, as lists work in a similar way and are more flexible to work with.

How to Use Arrays in Python

In order to create Python arrays, you'll first have to import the array module which contains all the necassary functions.

There are three ways you can import the array module:

  • By using import array at the top of the file. This includes the module array. You would then go on to create an array using array.array().
import array

#how you would create an array
array.array()
  • Instead of having to type array.array() all the time, you could use import array as arr at the top of the file, instead of import array alone. You would then create an array by typing arr.array(). The arr acts as an alias name, with the array constructor then immediately following it.
import array as arr

#how you would create an array
arr.array()
  • Lastly, you could also use from array import *, with * importing all the functionalities available. You would then create an array by writing the array() constructor alone.
from array import *

#how you would create an array
array()

How to Define Arrays in Python

Once you've imported the array module, you can then go on to define a Python array.

The general syntax for creating an array looks like this:

variable_name = array(typecode,[elements])

Let's break it down:

  • variable_name would be the name of the array.
  • The typecode specifies what kind of elements would be stored in the array. Whether it would be an array of integers, an array of floats or an array of any other Python data type. Remember that all elements should be of the same data type.
  • Inside square brackets you mention the elements that would be stored in the array, with each element being separated by a comma. You can also create an empty array by just writing variable_name = array(typecode) alone, without any elements.

Below is a typecode table, with the different typecodes that can be used with the different data types when defining Python arrays:

TYPECODEC TYPEPYTHON TYPESIZE
'b'signed charint1
'B'unsigned charint1
'u'wchar_tUnicode character2
'h'signed shortint2
'H'unsigned shortint2
'i'signed intint2
'I'unsigned intint2
'l'signed longint4
'L'unsigned longint4
'q'signed long longint8
'Q'unsigned long longint8
'f'floatfloat4
'd'doublefloat8

Tying everything together, here is an example of how you would define an array in Python:

import array as arr 

numbers = arr.array('i',[10,20,30])


print(numbers)

#output

#array('i', [10, 20, 30])

Let's break it down:

  • First we included the array module, in this case with import array as arr .
  • Then, we created a numbers array.
  • We used arr.array() because of import array as arr .
  • Inside the array() constructor, we first included i, for signed integer. Signed integer means that the array can include positive and negative values. Unsigned integer, with H for example, would mean that no negative values are allowed.
  • Lastly, we included the values to be stored in the array in square brackets.

Keep in mind that if you tried to include values that were not of i typecode, meaning they were not integer values, you would get an error:

import array as arr 

numbers = arr.array('i',[10.0,20,30])


print(numbers)

#output

#Traceback (most recent call last):
# File "/Users/dionysialemonaki/python_articles/demo.py", line 14, in <module>
#   numbers = arr.array('i',[10.0,20,30])
#TypeError: 'float' object cannot be interpreted as an integer

In the example above, I tried to include a floating point number in the array. I got an error because this is meant to be an integer array only.

Another way to create an array is the following:

from array import *

#an array of floating point values
numbers = array('d',[10.0,20.0,30.0])

print(numbers)

#output

#array('d', [10.0, 20.0, 30.0])

The example above imported the array module via from array import * and created an array numbers of float data type. This means that it holds only floating point numbers, which is specified with the 'd' typecode.

How to Find the Length of an Array in Python

To find out the exact number of elements contained in an array, use the built-in len() method.

It will return the integer number that is equal to the total number of elements in the array you specify.

import array as arr 

numbers = arr.array('i',[10,20,30])


print(len(numbers))

#output
# 3

In the example above, the array contained three elements – 10, 20, 30 – so the length of numbers is 3.

Array Indexing and How to Access Individual Items in an Array in Python

Each item in an array has a specific address. Individual items are accessed by referencing their index number.

Indexing in Python, and in all programming languages and computing in general, starts at 0. It is important to remember that counting starts at 0 and not at 1.

To access an element, you first write the name of the array followed by square brackets. Inside the square brackets you include the item's index number.

The general syntax would look something like this:

array_name[index_value_of_item]

Here is how you would access each individual element in an array:

import array as arr 

numbers = arr.array('i',[10,20,30])

print(numbers[0]) # gets the 1st element
print(numbers[1]) # gets the 2nd element
print(numbers[2]) # gets the 3rd element

#output

#10
#20
#30

Remember that the index value of the last element of an array is always one less than the length of the array. Where n is the length of the array, n - 1 will be the index value of the last item.

Note that you can also access each individual element using negative indexing.

With negative indexing, the last element would have an index of -1, the second to last element would have an index of -2, and so on.

Here is how you would get each item in an array using that method:

import array as arr 

numbers = arr.array('i',[10,20,30])

print(numbers[-1]) #gets last item
print(numbers[-2]) #gets second to last item
print(numbers[-3]) #gets first item
 
#output

#30
#20
#10

How to Search Through an Array in Python

You can find out an element's index number by using the index() method.

You pass the value of the element being searched as the argument to the method, and the element's index number is returned.

import array as arr 

numbers = arr.array('i',[10,20,30])

#search for the index of the value 10
print(numbers.index(10))

#output

#0

If there is more than one element with the same value, the index of the first instance of the value will be returned:

import array as arr 


numbers = arr.array('i',[10,20,30,10,20,30])

#search for the index of the value 10
#will return the index number of the first instance of the value 10
print(numbers.index(10))

#output

#0

How to Loop through an Array in Python

You've seen how to access each individual element in an array and print it out on its own.

You've also seen how to print the array, using the print() method. That method gives the following result:

import array as arr 

numbers = arr.array('i',[10,20,30])

print(numbers)

#output

#array('i', [10, 20, 30])

What if you want to print each value one by one?

This is where a loop comes in handy. You can loop through the array and print out each value, one-by-one, with each loop iteration.

For this you can use a simple for loop:

import array as arr 

numbers = arr.array('i',[10,20,30])

for number in numbers:
    print(number)
    
#output
#10
#20
#30

You could also use the range() function, and pass the len() method as its parameter. This would give the same result as above:

import array as arr  

values = arr.array('i',[10,20,30])

#prints each individual value in the array
for value in range(len(values)):
    print(values[value])

#output

#10
#20
#30

How to Slice an Array in Python

To access a specific range of values inside the array, use the slicing operator, which is a colon :.

When using the slicing operator and you only include one value, the counting starts from 0 by default. It gets the first item, and goes up to but not including the index number you specify.

import array as arr 

#original array
numbers = arr.array('i',[10,20,30])

#get the values 10 and 20 only
print(numbers[:2])  #first to second position

#output

#array('i', [10, 20])

When you pass two numbers as arguments, you specify a range of numbers. In this case, the counting starts at the position of the first number in the range, and up to but not including the second one:

import array as arr 

#original array
numbers = arr.array('i',[10,20,30])


#get the values 20 and 30 only
print(numbers[1:3]) #second to third position

#output

#rray('i', [20, 30])

Methods For Performing Operations on Arrays in Python

Arrays are mutable, which means they are changeable. You can change the value of the different items, add new ones, or remove any you don't want in your program anymore.

Let's see some of the most commonly used methods which are used for performing operations on arrays.

How to Change the Value of an Item in an Array

You can change the value of a specific element by speficying its position and assigning it a new value:

import array as arr 

#original array
numbers = arr.array('i',[10,20,30])

#change the first element
#change it from having a value of 10 to having a value of 40
numbers[0] = 40

print(numbers)

#output

#array('i', [40, 20, 30])

How to Add a New Value to an Array

To add one single value at the end of an array, use the append() method:

import array as arr 

#original array
numbers = arr.array('i',[10,20,30])

#add the integer 40 to the end of numbers
numbers.append(40)

print(numbers)

#output

#array('i', [10, 20, 30, 40])

Be aware that the new item you add needs to be the same data type as the rest of the items in the array.

Look what happens when I try to add a float to an array of integers:

import array as arr 

#original array
numbers = arr.array('i',[10,20,30])

#add the integer 40 to the end of numbers
numbers.append(40.0)

print(numbers)

#output

#Traceback (most recent call last):
#  File "/Users/dionysialemonaki/python_articles/demo.py", line 19, in <module>
#   numbers.append(40.0)
#TypeError: 'float' object cannot be interpreted as an integer

But what if you want to add more than one value to the end an array?

Use the extend() method, which takes an iterable (such as a list of items) as an argument. Again, make sure that the new items are all the same data type.

import array as arr 

#original array
numbers = arr.array('i',[10,20,30])

#add the integers 40,50,60 to the end of numbers
#The numbers need to be enclosed in square brackets

numbers.extend([40,50,60])

print(numbers)

#output

#array('i', [10, 20, 30, 40, 50, 60])

And what if you don't want to add an item to the end of an array? Use the insert() method, to add an item at a specific position.

The insert() function takes two arguments: the index number of the position the new element will be inserted, and the value of the new element.

import array as arr 

#original array
numbers = arr.array('i',[10,20,30])

#add the integer 40 in the first position
#remember indexing starts at 0

numbers.insert(0,40)

print(numbers)

#output

#array('i', [40, 10, 20, 30])

How to Remove a Value from an Array

To remove an element from an array, use the remove() method and include the value as an argument to the method.

import array as arr 

#original array
numbers = arr.array('i',[10,20,30])

numbers.remove(10)

print(numbers)

#output

#array('i', [20, 30])

With remove(), only the first instance of the value you pass as an argument will be removed.

See what happens when there are more than one identical values:

import array as arr 

#original array
numbers = arr.array('i',[10,20,30,10,20])

numbers.remove(10)

print(numbers)

#output

#array('i', [20, 30, 10, 20])

Only the first occurence of 10 is removed.

You can also use the pop() method, and specify the position of the element to be removed:

import array as arr 

#original array
numbers = arr.array('i',[10,20,30,10,20])

#remove the first instance of 10
numbers.pop(0)

print(numbers)

#output

#array('i', [20, 30, 10, 20])

Conclusion

And there you have it - you now know the basics of how to create arrays in Python using the array module. Hopefully you found this guide helpful.

Thanks for reading and happy coding!

#python #programming 

Connor Mills

Connor Mills

1670560264

Understanding Arrays in Python

Learn how to use Python arrays. Create arrays in Python using the array module. You'll see how to define them and the different methods commonly used for performing operations on them.
 

The artcile covers arrays that you create by importing the array module. We won't cover NumPy arrays here.

Table of Contents

  1. Introduction to Arrays
    1. The differences between Lists and Arrays
    2. When to use arrays
  2. How to use arrays
    1. Define arrays
    2. Find the length of arrays
    3. Array indexing
    4. Search through arrays
    5. Loop through arrays
    6. Slice an array
  3. Array methods for performing operations
    1. Change an existing value
    2. Add a new value
    3. Remove a value
  4. Conclusion

Let's get started!


What are Python Arrays?

Arrays are a fundamental data structure, and an important part of most programming languages. In Python, they are containers which are able to store more than one item at the same time.

Specifically, they are an ordered collection of elements with every value being of the same data type. That is the most important thing to remember about Python arrays - the fact that they can only hold a sequence of multiple items that are of the same type.

What's the Difference between Python Lists and Python Arrays?

Lists are one of the most common data structures in Python, and a core part of the language.

Lists and arrays behave similarly.

Just like arrays, lists are an ordered sequence of elements.

They are also mutable and not fixed in size, which means they can grow and shrink throughout the life of the program. Items can be added and removed, making them very flexible to work with.

However, lists and arrays are not the same thing.

Lists store items that are of various data types. This means that a list can contain integers, floating point numbers, strings, or any other Python data type, at the same time. That is not the case with arrays.

As mentioned in the section above, arrays store only items that are of the same single data type. There are arrays that contain only integers, or only floating point numbers, or only any other Python data type you want to use.

When to Use Python Arrays

Lists are built into the Python programming language, whereas arrays aren't. Arrays are not a built-in data structure, and therefore need to be imported via the array module in order to be used.

Arrays of the array module are a thin wrapper over C arrays, and are useful when you want to work with homogeneous data.

They are also more compact and take up less memory and space which makes them more size efficient compared to lists.

If you want to perform mathematical calculations, then you should use NumPy arrays by importing the NumPy package. Besides that, you should just use Python arrays when you really need to, as lists work in a similar way and are more flexible to work with.

How to Use Arrays in Python

In order to create Python arrays, you'll first have to import the array module which contains all the necassary functions.

There are three ways you can import the array module:

  1. By using import array at the top of the file. This includes the module array. You would then go on to create an array using array.array().
import array

#how you would create an array
array.array()
  1. Instead of having to type array.array() all the time, you could use import array as arr at the top of the file, instead of import array alone. You would then create an array by typing arr.array(). The arr acts as an alias name, with the array constructor then immediately following it.
import array as arr

#how you would create an array
arr.array()
  1. Lastly, you could also use from array import *, with * importing all the functionalities available. You would then create an array by writing the array() constructor alone.
from array import *

#how you would create an array
array()

How to Define Arrays in Python

Once you've imported the array module, you can then go on to define a Python array.

The general syntax for creating an array looks like this:

variable_name = array(typecode,[elements])

Let's break it down:

  • variable_name would be the name of the array.
  • The typecode specifies what kind of elements would be stored in the array. Whether it would be an array of integers, an array of floats or an array of any other Python data type. Remember that all elements should be of the same data type.
  • Inside square brackets you mention the elements that would be stored in the array, with each element being separated by a comma. You can also create an empty array by just writing variable_name = array(typecode) alone, without any elements.

Below is a typecode table, with the different typecodes that can be used with the different data types when defining Python arrays:

TYPECODEC TYPEPYTHON TYPESIZE
'b'signed charint1
'B'unsigned charint1
'u'wchar_tUnicode character2
'h'signed shortint2
'H'unsigned shortint2
'i'signed intint2
'I'unsigned intint2
'l'signed longint4
'L'unsigned longint4
'q'signed long longint8
'Q'unsigned long longint8
'f'floatfloat4
'd'doublefloat8

Tying everything together, here is an example of how you would define an array in Python:

import array as arr 

numbers = arr.array('i',[10,20,30])


print(numbers)

#output

#array('i', [10, 20, 30])

Let's break it down:

  • First we included the array module, in this case with import array as arr .
  • Then, we created a numbers array.
  • We used arr.array() because of import array as arr .
  • Inside the array() constructor, we first included i, for signed integer. Signed integer means that the array can include positive and negative values. Unsigned integer, with H for example, would mean that no negative values are allowed.
  • Lastly, we included the values to be stored in the array in square brackets.

Keep in mind that if you tried to include values that were not of i typecode, meaning they were not integer values, you would get an error:

import array as arr 

numbers = arr.array('i',[10.0,20,30])


print(numbers)

#output

#Traceback (most recent call last):
# File "/Users/dionysialemonaki/python_articles/demo.py", line 14, in <module>
#   numbers = arr.array('i',[10.0,20,30])
#TypeError: 'float' object cannot be interpreted as an integer

In the example above, I tried to include a floating point number in the array. I got an error because this is meant to be an integer array only.

Another way to create an array is the following:

from array import *

#an array of floating point values
numbers = array('d',[10.0,20.0,30.0])

print(numbers)

#output

#array('d', [10.0, 20.0, 30.0])

The example above imported the array module via from array import * and created an array numbers of float data type. This means that it holds only floating point numbers, which is specified with the 'd' typecode.

How to Find the Length of an Array in Python

To find out the exact number of elements contained in an array, use the built-in len() method.

It will return the integer number that is equal to the total number of elements in the array you specify.

import array as arr 

numbers = arr.array('i',[10,20,30])


print(len(numbers))

#output
# 3

In the example above, the array contained three elements – 10, 20, 30 – so the length of numbers is 3.

Array Indexing and How to Access Individual Items in an Array in Python

Each item in an array has a specific address. Individual items are accessed by referencing their index number.

Indexing in Python, and in all programming languages and computing in general, starts at 0. It is important to remember that counting starts at 0 and not at 1.

To access an element, you first write the name of the array followed by square brackets. Inside the square brackets you include the item's index number.

The general syntax would look something like this:

array_name[index_value_of_item]

Here is how you would access each individual element in an array:

import array as arr 

numbers = arr.array('i',[10,20,30])

print(numbers[0]) # gets the 1st element
print(numbers[1]) # gets the 2nd element
print(numbers[2]) # gets the 3rd element

#output

#10
#20
#30

Remember that the index value of the last element of an array is always one less than the length of the array. Where n is the length of the array, n - 1 will be the index value of the last item.

Note that you can also access each individual element using negative indexing.

With negative indexing, the last element would have an index of -1, the second to last element would have an index of -2, and so on.

Here is how you would get each item in an array using that method:

import array as arr 

numbers = arr.array('i',[10,20,30])

print(numbers[-1]) #gets last item
print(numbers[-2]) #gets second to last item
print(numbers[-3]) #gets first item
 
#output

#30
#20
#10

How to Search Through an Array in Python

You can find out an element's index number by using the index() method.

You pass the value of the element being searched as the argument to the method, and the element's index number is returned.

import array as arr 

numbers = arr.array('i',[10,20,30])

#search for the index of the value 10
print(numbers.index(10))

#output

#0

If there is more than one element with the same value, the index of the first instance of the value will be returned:

import array as arr 


numbers = arr.array('i',[10,20,30,10,20,30])

#search for the index of the value 10
#will return the index number of the first instance of the value 10
print(numbers.index(10))

#output

#0

How to Loop through an Array in Python

You've seen how to access each individual element in an array and print it out on its own.

You've also seen how to print the array, using the print() method. That method gives the following result:

import array as arr 

numbers = arr.array('i',[10,20,30])

print(numbers)

#output

#array('i', [10, 20, 30])

What if you want to print each value one by one?

This is where a loop comes in handy. You can loop through the array and print out each value, one-by-one, with each loop iteration.

For this you can use a simple for loop:

import array as arr 

numbers = arr.array('i',[10,20,30])

for number in numbers:
    print(number)
    
#output
#10
#20
#30

You could also use the range() function, and pass the len() method as its parameter. This would give the same result as above:

import array as arr  

values = arr.array('i',[10,20,30])

#prints each individual value in the array
for value in range(len(values)):
    print(values[value])

#output

#10
#20
#30

How to Slice an Array in Python

To access a specific range of values inside the array, use the slicing operator, which is a colon :.

When using the slicing operator and you only include one value, the counting starts from 0 by default. It gets the first item, and goes up to but not including the index number you specify.


import array as arr 

#original array
numbers = arr.array('i',[10,20,30])

#get the values 10 and 20 only
print(numbers[:2])  #first to second position

#output

#array('i', [10, 20])

When you pass two numbers as arguments, you specify a range of numbers. In this case, the counting starts at the position of the first number in the range, and up to but not including the second one:

import array as arr 

#original array
numbers = arr.array('i',[10,20,30])


#get the values 20 and 30 only
print(numbers[1:3]) #second to third position

#output

#rray('i', [20, 30])

Methods For Performing Operations on Arrays in Python

Arrays are mutable, which means they are changeable. You can change the value of the different items, add new ones, or remove any you don't want in your program anymore.

Let's see some of the most commonly used methods which are used for performing operations on arrays.

How to Change the Value of an Item in an Array

You can change the value of a specific element by speficying its position and assigning it a new value:

import array as arr 

#original array
numbers = arr.array('i',[10,20,30])

#change the first element
#change it from having a value of 10 to having a value of 40
numbers[0] = 40

print(numbers)

#output

#array('i', [40, 20, 30])

How to Add a New Value to an Array

To add one single value at the end of an array, use the append() method:

import array as arr 

#original array
numbers = arr.array('i',[10,20,30])

#add the integer 40 to the end of numbers
numbers.append(40)

print(numbers)

#output

#array('i', [10, 20, 30, 40])

Be aware that the new item you add needs to be the same data type as the rest of the items in the array.

Look what happens when I try to add a float to an array of integers:

import array as arr 

#original array
numbers = arr.array('i',[10,20,30])

#add the integer 40 to the end of numbers
numbers.append(40.0)

print(numbers)

#output

#Traceback (most recent call last):
#  File "/Users/dionysialemonaki/python_articles/demo.py", line 19, in <module>
#   numbers.append(40.0)
#TypeError: 'float' object cannot be interpreted as an integer

But what if you want to add more than one value to the end an array?

Use the extend() method, which takes an iterable (such as a list of items) as an argument. Again, make sure that the new items are all the same data type.

import array as arr 

#original array
numbers = arr.array('i',[10,20,30])

#add the integers 40,50,60 to the end of numbers
#The numbers need to be enclosed in square brackets

numbers.extend([40,50,60])

print(numbers)

#output

#array('i', [10, 20, 30, 40, 50, 60])

And what if you don't want to add an item to the end of an array? Use the insert() method, to add an item at a specific position.

The insert() function takes two arguments: the index number of the position the new element will be inserted, and the value of the new element.

import array as arr 

#original array
numbers = arr.array('i',[10,20,30])

#add the integer 40 in the first position
#remember indexing starts at 0

numbers.insert(0,40)

print(numbers)

#output

#array('i', [40, 10, 20, 30])

How to Remove a Value from an Array

To remove an element from an array, use the remove() method and include the value as an argument to the method.

import array as arr 

#original array
numbers = arr.array('i',[10,20,30])

numbers.remove(10)

print(numbers)

#output

#array('i', [20, 30])

With remove(), only the first instance of the value you pass as an argument will be removed.

See what happens when there are more than one identical values:


import array as arr 

#original array
numbers = arr.array('i',[10,20,30,10,20])

numbers.remove(10)

print(numbers)

#output

#array('i', [20, 30, 10, 20])

Only the first occurence of 10 is removed.

You can also use the pop() method, and specify the position of the element to be removed:

import array as arr 

#original array
numbers = arr.array('i',[10,20,30,10,20])

#remove the first instance of 10
numbers.pop(0)

print(numbers)

#output

#array('i', [20, 30, 10, 20])

Conclusion

And there you have it - you now know the basics of how to create arrays in Python using the array module. Hopefully you found this guide helpful.

You'll start from the basics and learn in an interacitve and beginner-friendly way. You'll also build five projects at the end to put into practice and help reinforce what you learned.

Thanks for reading and happy coding!

Original article source at https://www.freecodecamp.org

#python 

田辺  亮介

田辺 亮介

1662351030

Python中最常用的數據結構

在任何編程語言中,我們都需要處理數據。現在,我們需要處理數據的最基本的事情之一就是以有組織的方式有效地存儲、管理和訪問它,以便我們可以在需要時將其用於我們的目的。數據結構用於滿足我們所有的需求。

什麼是數據結構?

數據結構是編程語言的基本構建塊。它旨在提供一種系統的方法來滿足本文前面提到的所有要求。Python 中的數據結構是List、Tuple、Dictionary 和 Set。它們被視為Python 中的隱式或內置數據結構。我們可以使用這些數據結構並對它們應用多種方法來管理、關聯、操作和利用我們的數據。

我們還有用戶定義的自定義數據結構,即StackQueueTreeLinked ListGraph。它們允許用戶完全控制其功能並將其用於高級編程目的。但是,我們將專注於本文的內置數據結構。

隱式數據結構 Python

隱式數據結構 Python

列表

列表幫助我們以多種數據類型順序存儲數據。它們類似於數組,除了它們可以同時存儲不同的數據類型,如字符串和數字。列表中的每個項目或元素都有一個指定的索引。由於Python 使用基於 0 的索引,因此第一個元素的索引為 0,並且繼續計數。列表的最後一個元素以 -1 開頭,可用於訪問從最後一個到第一個的元素。要創建一個列表,我們必須將項目寫在方括號內

關於列表要記住的最重要的事情之一是它們是可變的。這僅僅意味著我們可以通過使用索引運算符直接訪問它作為賦值語句的一部分來更改列表中的元素。我們還可以對列表執行操作以獲得所需的輸出。讓我們通過代碼來更好地理解列表和列表操作。

1. 創建列表

#creating the list
my_list = ['p', 'r', 'o', 'b', 'e']
print(my_list)

輸出

['p', 'r', 'o', 'b', 'e']

2. 訪問列表中的項目

#accessing the list 
 
#accessing the first item of the list
my_list[0]

輸出

'p'
#accessing the third item of the list
my_list[2]
'o'

3. 向列表中添加新項目

#adding item to the list
my_list + ['k']

輸出

['p', 'r', 'o', 'b', 'e', 'k']

4. 移除物品

#removing item from the list
#Method 1:
 
#Deleting list items
my_list = ['p', 'r', 'o', 'b', 'l', 'e', 'm']
 
# delete one item
del my_list[2]
 
print(my_list)
 
# delete multiple items
del my_list[1:5]
 
print(my_list)

輸出

['p', 'r', 'b', 'l', 'e', 'm']
['p', 'm']
#Method 2:
 
#with remove fucntion
my_list = ['p','r','o','k','l','y','m']
my_list.remove('p')
 
 
print(my_list)
 
#Method 3:
 
#with pop function
print(my_list.pop(1))
 
# Output: ['r', 'k', 'l', 'y', 'm']
print(my_list)

輸出

['r', 'o', 'k', 'l', 'y', 'm']
o
['r', 'k', 'l', 'y', 'm']

5.排序列表

#sorting of list in ascending order
 
my_list.sort()
print(my_list)

輸出

['k', 'l', 'm', 'r', 'y']
#sorting of list in descending order
 
my_list.sort(reverse=True)
print(my_list)

輸出

['y', 'r', 'm', 'l', 'k']

6. 查找列表的長度

#finding the length of list
 
len(my_list)

輸出

5

元組

元組與列表非常相似,關鍵區別在於元組是 IMMUTABLE,與列表不同。一旦我們創建了一個元組或有一個元組,我們就不能改變它裡面的元素。但是,如果我們在元組中有一個元素,它本身就是一個列表,那麼我們只能在該列表中訪問或更改。要創建一個元組,我們必須在括號內寫入項目。像列表一樣,我們有類似的方法可以用於元組。讓我們通過一些代碼片段來理解使用元組。

1. 創建一個元組

#creating of tuple
 
my_tuple = ("apple", "banana", "guava")
print(my_tuple)

輸出

('apple', 'banana', 'guava')

2. 從元組訪問項目

#accessing first element in tuple
 
my_tuple[1]

輸出

'banana'

3. 元組的長度

#for finding the lenght of tuple
 
len(my_tuple)

輸出

3

4. 將元組轉換為列表

#converting tuple into a list
 
my_tuple_list = list(my_tuple)
type(my_tuple_list)

輸出

list

5. 反轉元組

#Reversing a tuple
 
tuple(sorted(my_tuple, reverse=True)) 

輸出

('guava', 'banana', 'apple')

6. 對元組進行排序

#sorting tuple in ascending order
 
tuple(sorted(my_tuple)) 

輸出

('apple', 'banana', 'guava')

7. 從元組中刪除元素

為了從元組中刪除元素,我們首先將元組轉換為列表,就像我們在上面的方法之一(第 4 點)中所做的那樣,然後遵循列表的相同過程,並顯式刪除整個元組,只需使用del聲明

字典

字典是一個集合,它只是意味著它用於存儲帶有某個鍵的值並提取給定鍵的值。我們可以將其視為一組鍵:值對 和字典中的每個都應該是唯一的,以便我們可以相應地訪問相應的

字典由包含鍵:值對的花括號 { }表示。字典中的每一對都以逗號分隔。字典中的元素是無序的,當我們訪問或存儲它們時,序列並不重要。

它們是可變的,這意味著我們可以在字典中添加、刪除或更新元素。以下是一些代碼示例,可以更好地理解 python 中的字典。

需要注意的重要一點是,我們不能將可變對像用作字典中的鍵。因此,列表不允許作為字典中的鍵。

1. 創建字典

#creating a dictionary
 
my_dict = {
    1:'Delhi',
    2:'Patna',
    3:'Bangalore'
}
print(my_dict)

輸出

{1: 'Delhi', 2: 'Patna', 3: 'Bangalore'}

這裡,整數是字典的鍵,與整數相關的城市名稱是字典的值。

2. 從字典中訪問項目

#access an item
 
print(my_dict[1])

輸出

'Delhi'

3. 字典的長度

#length of the dictionary
 
len(my_dict)

輸出

3

4. 對字典進行排序

#sorting based on the key 
 
Print(sorted(my_dict.items()))
 
 
#sorting based on the values of dictionary
 
print(sorted(my_dict.values()))

輸出

[(1, 'Delhi'), (2, 'Bangalore'), (3, 'Patna')]
 
['Bangalore', 'Delhi', 'Patna']

5. 在字典中添加元素

#adding a new item in dictionary 
 
my_dict[4] = 'Lucknow'
print(my_dict)

輸出

{1: 'Delhi', 2: 'Patna', 3: 'Bangalore', 4: 'Lucknow'}

6.從字典中刪除元素

#for deleting an item from dict using the specific key
 
my_dict.pop(4)
print(my_dict)
 
#for deleting last item from the list
 
my_dict.popitem()
 
#for clearing the dictionary
 
my_dict.clear()
print(my_dict)

輸出

{1: 'Delhi', 2: 'Patna', 3: 'Bangalore'}
(3, 'Bangalore')
{}

Set 是 python 中的另一種數據類型,它是一個沒有重複元素的無序集合。集合的常見用例是刪除重複值並執行成員資格測試。花括號set()函數可用於創建集合。要記住的一件事是,在創建空集時,我們必須使用set(),。後者創建一個空字典。 not { }

以下是一些代碼示例,可幫助您更好地理解 Python 中的集合。

1. 創建一個 集合

#creating set
 
my_set = {"apple", "mango", "strawberry", "apple"}
print(my_set)

輸出

{'apple', 'strawberry', 'mango'}

2. 訪問集合中的項目

#to test for an element inside the set
 
"apple" in my_set

輸出

True

3. 集合的長度

print(len(my_set))

輸出

3

4. 對集合進行排序

print(sorted(my_set))

輸出

['apple', 'mango', 'strawberry']

5. 在Set中添加元素

my_set.add("guava")
print(my_set)

輸出

{'apple', 'guava', 'mango', 'strawberry'}

6. 從 Set 中移除元素

my_set.remove("mango")
print(my_set)

輸出

{'apple', 'guava', 'strawberry'}

結論

在本文中,我們瀏覽了 Python 中最常用的數據結構,並了解了與它們相關的各種方法。

鏈接:https ://www.askpython.com/python/data

#python #datastructures

Thierry  Perret

Thierry Perret

1662365538

Les Structures De Données Les Plus Couramment Utilisées En Python

Dans tout langage de programmation, nous devons traiter des données. Maintenant, l'une des choses les plus fondamentales dont nous avons besoin pour travailler avec les données est de les stocker, de les gérer et d'y accéder efficacement de manière organisée afin qu'elles puissent être utilisées chaque fois que cela est nécessaire pour nos besoins. Les structures de données sont utilisées pour répondre à tous nos besoins.

Que sont les Structures de Données ?

Les structures de données sont les blocs de construction fondamentaux d'un langage de programmation. Il vise à fournir une approche systématique pour répondre à toutes les exigences mentionnées précédemment dans l'article. Les structures de données en Python sont List, Tuple, Dictionary et Set . Ils sont considérés comme des structures de données implicites ou intégrées dans Python . Nous pouvons utiliser ces structures de données et leur appliquer de nombreuses méthodes pour gérer, relier, manipuler et utiliser nos données.

Nous avons également des structures de données personnalisées définies par l'utilisateur, à savoir Stack , Queue , Tree , Linked List et Graph . Ils permettent aux utilisateurs d'avoir un contrôle total sur leurs fonctionnalités et de les utiliser à des fins de programmation avancées. Cependant, nous nous concentrerons sur les structures de données intégrées pour cet article.

Structures de données implicites Python

Structures de données implicites Python

LISTE

Les listes nous aident à stocker nos données de manière séquentielle avec plusieurs types de données. Ils sont comparables aux tableaux à l'exception qu'ils peuvent stocker différents types de données comme des chaînes et des nombres en même temps. Chaque élément ou élément d'une liste a un index attribué. Étant donné que Python utilise l' indexation basée sur 0 , le premier élément a un index de 0 et le comptage continue. Le dernier élément d'une liste commence par -1 qui peut être utilisé pour accéder aux éléments du dernier au premier. Pour créer une liste, nous devons écrire les éléments à l'intérieur des crochets .

L'une des choses les plus importantes à retenir à propos des listes est qu'elles sont Mutable . Cela signifie simplement que nous pouvons modifier un élément dans une liste en y accédant directement dans le cadre de l'instruction d'affectation à l'aide de l'opérateur d'indexation. Nous pouvons également effectuer des opérations sur notre liste pour obtenir la sortie souhaitée. Passons en revue le code pour mieux comprendre les opérations de liste et de liste.

1. Créer une liste

#creating the list
my_list = ['p', 'r', 'o', 'b', 'e']
print(my_list)

Production

['p', 'r', 'o', 'b', 'e']

2. Accéder aux éléments de la liste

#accessing the list 
 
#accessing the first item of the list
my_list[0]

Production

'p'
#accessing the third item of the list
my_list[2]
'o'

3. Ajouter de nouveaux éléments à la liste

#adding item to the list
my_list + ['k']

Production

['p', 'r', 'o', 'b', 'e', 'k']

4. Suppression d'éléments

#removing item from the list
#Method 1:
 
#Deleting list items
my_list = ['p', 'r', 'o', 'b', 'l', 'e', 'm']
 
# delete one item
del my_list[2]
 
print(my_list)
 
# delete multiple items
del my_list[1:5]
 
print(my_list)

Production

['p', 'r', 'b', 'l', 'e', 'm']
['p', 'm']
#Method 2:
 
#with remove fucntion
my_list = ['p','r','o','k','l','y','m']
my_list.remove('p')
 
 
print(my_list)
 
#Method 3:
 
#with pop function
print(my_list.pop(1))
 
# Output: ['r', 'k', 'l', 'y', 'm']
print(my_list)

Production

['r', 'o', 'k', 'l', 'y', 'm']
o
['r', 'k', 'l', 'y', 'm']

5. Liste de tri

#sorting of list in ascending order
 
my_list.sort()
print(my_list)

Production

['k', 'l', 'm', 'r', 'y']
#sorting of list in descending order
 
my_list.sort(reverse=True)
print(my_list)

Production

['y', 'r', 'm', 'l', 'k']

6. Trouver la longueur d'une liste

#finding the length of list
 
len(my_list)

Production

5

TUPLE

Les tuples sont très similaires aux listes avec une différence clé qu'un tuple est IMMUTABLE , contrairement à une liste. Une fois que nous avons créé un tuple ou que nous avons un tuple, nous ne sommes pas autorisés à modifier les éléments qu'il contient. Cependant, si nous avons un élément à l'intérieur d'un tuple, qui est une liste elle-même, alors seulement nous pouvons accéder ou changer dans cette liste. Pour créer un tuple, nous devons écrire les éléments entre parenthèses . Comme les listes, nous avons des méthodes similaires qui peuvent être utilisées avec des tuples. Passons en revue quelques extraits de code pour comprendre l'utilisation des tuples.

1. Créer un tuple

#creating of tuple
 
my_tuple = ("apple", "banana", "guava")
print(my_tuple)

Production

('apple', 'banana', 'guava')

2. Accéder aux éléments d'un Tuple

#accessing first element in tuple
 
my_tuple[1]

Production

'banana'

3. Longueur d'un tuple

#for finding the lenght of tuple
 
len(my_tuple)

Production

3

4. Conversion d'un tuple en liste

#converting tuple into a list
 
my_tuple_list = list(my_tuple)
type(my_tuple_list)

Production

list

5. Inverser un tuple

#Reversing a tuple
 
tuple(sorted(my_tuple, reverse=True)) 

Production

('guava', 'banana', 'apple')

6. Trier un tuple

#sorting tuple in ascending order
 
tuple(sorted(my_tuple)) 

Production

('apple', 'banana', 'guava')

7. Supprimer des éléments de Tuple

Pour supprimer des éléments du tuple, nous avons d'abord converti le tuple en une liste comme nous l'avons fait dans l'une de nos méthodes ci-dessus (point n ° 4), puis avons suivi le même processus de la liste et avons explicitement supprimé un tuple entier, juste en utilisant le del déclaration .

DICTIONNAIRE

Dictionary est une collection, ce qui signifie simplement qu'il est utilisé pour stocker une valeur avec une clé et extraire la valeur donnée à la clé. Nous pouvons le considérer comme un ensemble de clés : des paires de valeurs et chaque clé d'un dictionnaire est supposée être unique afin que nous puissions accéder aux valeurs correspondantes en conséquence.

Un dictionnaire est indiqué par l'utilisation d' accolades { } contenant les paires clé : valeur. Chacune des paires d'un dictionnaire est séparée par des virgules. Les éléments d'un dictionnaire ne sont pas ordonnés , la séquence n'a pas d'importance pendant que nous y accédons ou que nous les stockons.

Ils sont MUTABLES ce qui signifie que nous pouvons ajouter, supprimer ou mettre à jour des éléments dans un dictionnaire. Voici quelques exemples de code pour mieux comprendre un dictionnaire en python.

Un point important à noter est que nous ne pouvons pas utiliser un objet mutable comme clé dans le dictionnaire. Ainsi, une liste n'est pas autorisée comme clé dans le dictionnaire.

1. Création d'un dictionnaire

#creating a dictionary
 
my_dict = {
    1:'Delhi',
    2:'Patna',
    3:'Bangalore'
}
print(my_dict)

Production

{1: 'Delhi', 2: 'Patna', 3: 'Bangalore'}

Ici, les entiers sont les clés du dictionnaire et le nom de ville associé aux entiers sont les valeurs du dictionnaire.

2. Accéder aux éléments d'un dictionnaire

#access an item
 
print(my_dict[1])

Production

'Delhi'

3. Longueur d'un dictionnaire

#length of the dictionary
 
len(my_dict)

Production

3

4. Trier un dictionnaire

#sorting based on the key 
 
Print(sorted(my_dict.items()))
 
 
#sorting based on the values of dictionary
 
print(sorted(my_dict.values()))

Production

[(1, 'Delhi'), (2, 'Bangalore'), (3, 'Patna')]
 
['Bangalore', 'Delhi', 'Patna']

5. Ajout d'éléments dans le dictionnaire

#adding a new item in dictionary 
 
my_dict[4] = 'Lucknow'
print(my_dict)

Production

{1: 'Delhi', 2: 'Patna', 3: 'Bangalore', 4: 'Lucknow'}

6. Suppression d'éléments du dictionnaire

#for deleting an item from dict using the specific key
 
my_dict.pop(4)
print(my_dict)
 
#for deleting last item from the list
 
my_dict.popitem()
 
#for clearing the dictionary
 
my_dict.clear()
print(my_dict)

Production

{1: 'Delhi', 2: 'Patna', 3: 'Bangalore'}
(3, 'Bangalore')
{}

POSITIONNER

Set est un autre type de données en python qui est une collection non ordonnée sans éléments en double. Les cas d'utilisation courants d'un ensemble consistent à supprimer les valeurs en double et à effectuer des tests d'appartenance. Les accolades ou la set()fonction peuvent être utilisées pour créer des ensembles. Une chose à garder à l'esprit est que lors de la création d'un ensemble vide, nous devons utiliser set(), et . Ce dernier crée un dictionnaire vide. not { }

Voici quelques exemples de code pour mieux comprendre les ensembles en python.

1. Créer un ensemble

#creating set
 
my_set = {"apple", "mango", "strawberry", "apple"}
print(my_set)

Production

{'apple', 'strawberry', 'mango'}

2. Accéder aux éléments d'un ensemble

#to test for an element inside the set
 
"apple" in my_set

Production

True

3. Longueur d'un ensemble

print(len(my_set))

Production

3

4. Trier un ensemble

print(sorted(my_set))

Production

['apple', 'mango', 'strawberry']

5. Ajout d'éléments dans Set

my_set.add("guava")
print(my_set)

Production

{'apple', 'guava', 'mango', 'strawberry'}

6. Suppression d'éléments de Set

my_set.remove("mango")
print(my_set)

Production

{'apple', 'guava', 'strawberry'}

Conclusion

Dans cet article, nous avons passé en revue les structures de données les plus couramment utilisées en python et avons également vu diverses méthodes qui leur sont associées.

Lien : https://www.askpython.com/python/data

#python #datastructures

Наиболее часто используемые структуры данных в Python

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

Что такое структуры данных?

Структуры данных являются фундаментальными строительными блоками языка программирования. Он направлен на обеспечение системного подхода для выполнения всех требований, упомянутых ранее в статье. Структуры данных в Python — это List, Tuple, Dictionary и Set . Они считаются неявными или встроенными структурами данных в Python . Мы можем использовать эти структуры данных и применять к ним многочисленные методы для управления, связывания, манипулирования и использования наших данных.

У нас также есть пользовательские структуры данных, определяемые пользователем, а именно Stack , Queue , Tree , Linked List и Graph . Они позволяют пользователям полностью контролировать их функциональность и использовать их для расширенных целей программирования. Однако в этой статье мы сосредоточимся на встроенных структурах данных.

Неявные структуры данных Python

Неявные структуры данных Python

СПИСОК

Списки помогают нам хранить наши данные последовательно с несколькими типами данных. Они сопоставимы с массивами за исключением того, что они могут одновременно хранить разные типы данных, такие как строки и числа. Каждый элемент или элемент в списке имеет назначенный индекс. Поскольку Python использует индексацию на основе 0, первый элемент имеет индекс 0, и подсчет продолжается. Последний элемент списка начинается с -1, что можно использовать для доступа к элементам от последнего к первому. Чтобы создать список, мы должны написать элементы внутри квадратных скобок .

Одна из самых важных вещей, которые нужно помнить о списках , это то, что они изменяемы . Это просто означает, что мы можем изменить элемент в списке, обратившись к нему напрямую как часть оператора присваивания с помощью оператора индексации. Мы также можем выполнять операции в нашем списке, чтобы получить желаемый результат. Давайте рассмотрим код, чтобы лучше понять список и операции со списками.

1. Создание списка

#creating the list
my_list = ['p', 'r', 'o', 'b', 'e']
print(my_list)

Выход

['p', 'r', 'o', 'b', 'e']

2. Доступ к элементам из списка

#accessing the list 
 
#accessing the first item of the list
my_list[0]

Выход

'p'
#accessing the third item of the list
my_list[2]
'o'

3. Добавление новых элементов в список

#adding item to the list
my_list + ['k']

Выход

['p', 'r', 'o', 'b', 'e', 'k']

4. Удаление элементов

#removing item from the list
#Method 1:
 
#Deleting list items
my_list = ['p', 'r', 'o', 'b', 'l', 'e', 'm']
 
# delete one item
del my_list[2]
 
print(my_list)
 
# delete multiple items
del my_list[1:5]
 
print(my_list)

Выход

['p', 'r', 'b', 'l', 'e', 'm']
['p', 'm']
#Method 2:
 
#with remove fucntion
my_list = ['p','r','o','k','l','y','m']
my_list.remove('p')
 
 
print(my_list)
 
#Method 3:
 
#with pop function
print(my_list.pop(1))
 
# Output: ['r', 'k', 'l', 'y', 'm']
print(my_list)

Выход

['r', 'o', 'k', 'l', 'y', 'm']
o
['r', 'k', 'l', 'y', 'm']

5. Список сортировки

#sorting of list in ascending order
 
my_list.sort()
print(my_list)

Выход

['k', 'l', 'm', 'r', 'y']
#sorting of list in descending order
 
my_list.sort(reverse=True)
print(my_list)

Выход

['y', 'r', 'm', 'l', 'k']

6. Нахождение длины списка

#finding the length of list
 
len(my_list)

Выход

5

КОРТЕЖ

Кортежи очень похожи на списки с той ключевой разницей, что кортеж является IMMUTABLE , в отличие от списка. Как только мы создаем кортеж или имеем кортеж, нам не разрешается изменять элементы внутри него. Однако если у нас есть элемент внутри кортежа, который сам является списком, только тогда мы можем получить доступ к этому списку или изменить его. Чтобы создать кортеж, мы должны написать элементы внутри круглых скобок . Как и со списками, у нас есть аналогичные методы, которые можно использовать с кортежами. Давайте рассмотрим некоторые фрагменты кода, чтобы понять, как использовать кортежи.

1. Создание кортежа

#creating of tuple
 
my_tuple = ("apple", "banana", "guava")
print(my_tuple)

Выход

('apple', 'banana', 'guava')

2. Доступ к элементам из кортежа

#accessing first element in tuple
 
my_tuple[1]

Выход

'banana'

3. Длина кортежа

#for finding the lenght of tuple
 
len(my_tuple)

Выход

3

4. Преобразование кортежа в список

#converting tuple into a list
 
my_tuple_list = list(my_tuple)
type(my_tuple_list)

Выход

list

5. Реверс кортежа

#Reversing a tuple
 
tuple(sorted(my_tuple, reverse=True)) 

Выход

('guava', 'banana', 'apple')

6. Сортировка кортежа

#sorting tuple in ascending order
 
tuple(sorted(my_tuple)) 

Выход

('apple', 'banana', 'guava')

7. Удаление элементов из кортежа

Для удаления элементов из кортежа мы сначала преобразовали кортеж в список, как мы сделали в одном из наших методов выше (пункт № 4), затем следовали тому же процессу списка и явно удалили весь кортеж, просто используя del заявление .

ТОЛКОВЫЙ СЛОВАРЬ

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

Словарь обозначается фигурными скобками { } , содержащими пары ключ: значение. Каждая из пар в словаре разделена запятой. Элементы в словаре неупорядочены , последовательность не имеет значения, пока мы обращаемся к ним или сохраняем их.

Они ИЗМЕНЯЕМЫ , что означает, что мы можем добавлять, удалять или обновлять элементы в словаре. Вот несколько примеров кода, чтобы лучше понять словарь в Python.

Важно отметить, что мы не можем использовать изменяемый объект в качестве ключа в словаре. Таким образом, список не допускается в качестве ключа в словаре.

1. Создание словаря

#creating a dictionary
 
my_dict = {
    1:'Delhi',
    2:'Patna',
    3:'Bangalore'
}
print(my_dict)

Выход

{1: 'Delhi', 2: 'Patna', 3: 'Bangalore'}

Здесь целые числа — это ключи словаря, а название города, связанное с целыми числами, — это значения словаря.

2. Доступ к элементам из словаря

#access an item
 
print(my_dict[1])

Выход

'Delhi'

3. Длина словаря

#length of the dictionary
 
len(my_dict)

Выход

3

4. Сортировка словаря

#sorting based on the key 
 
Print(sorted(my_dict.items()))
 
 
#sorting based on the values of dictionary
 
print(sorted(my_dict.values()))

Выход

[(1, 'Delhi'), (2, 'Bangalore'), (3, 'Patna')]
 
['Bangalore', 'Delhi', 'Patna']

5. Добавление элементов в Словарь

#adding a new item in dictionary 
 
my_dict[4] = 'Lucknow'
print(my_dict)

Выход

{1: 'Delhi', 2: 'Patna', 3: 'Bangalore', 4: 'Lucknow'}

6. Удаление элементов из словаря

#for deleting an item from dict using the specific key
 
my_dict.pop(4)
print(my_dict)
 
#for deleting last item from the list
 
my_dict.popitem()
 
#for clearing the dictionary
 
my_dict.clear()
print(my_dict)

Выход

{1: 'Delhi', 2: 'Patna', 3: 'Bangalore'}
(3, 'Bangalore')
{}

УСТАНОВЛЕН

Set — это еще один тип данных в python, представляющий собой неупорядоченную коллекцию без повторяющихся элементов. Общие варианты использования набора — удаление повторяющихся значений и проверка принадлежности. Фигурные скобки или set()функция могут использоваться для создания наборов. Следует иметь в виду, что при создании пустого набора мы должны использовать set(), и . Последний создает пустой словарь. not { }

Вот несколько примеров кода, чтобы лучше понять наборы в python.

1. Создание набора

#creating set
 
my_set = {"apple", "mango", "strawberry", "apple"}
print(my_set)

Выход

{'apple', 'strawberry', 'mango'}

2. Доступ к элементам из набора

#to test for an element inside the set
 
"apple" in my_set

Выход

True

3. Длина набора

print(len(my_set))

Выход

3

4. Сортировка набора

print(sorted(my_set))

Выход

['apple', 'mango', 'strawberry']

5. Добавление элементов в Set

my_set.add("guava")
print(my_set)

Выход

{'apple', 'guava', 'mango', 'strawberry'}

6. Удаление элементов из Set

my_set.remove("mango")
print(my_set)

Выход

{'apple', 'guava', 'strawberry'}

Вывод

В этой статье мы рассмотрели наиболее часто используемые структуры данных в Python, а также рассмотрели различные связанные с ними методы.

Ссылка: https://www.askpython.com/python/data

#python #datastructures