1600544520
In this article, we will look at how we can add an “edit post” button, to your Gatsby blog. When this button is clicked it will take the user to your markdown file, on github/gitlab that was used to generate the blog post they are currently viewing.
Before we add the edit button to a Gatsby blog, let’s set up a simple Gatsby site using the Gatsby blog starter
. You can skip this step and add the button to an existing site.
npm -g install gatsby-cli
gatsby new my-blog-starter https://github.com/gatsbyjs/gatsby-starter-blog
If you don’t use the start above, you will need to make sure you have the gatsby-source-filesystem
plugin installed. To import our markdown files. Your gatsby-config.js
looks like this:
{
resolve: `gatsby-source-filesystem`,
options: {
path: `${__dirname}/content/blog`,
name: `blog`,
},
},
Then make sure you also have the gatsby-transformer-remark
plugin installed and it should be in your gatsby-config.js
like so:
{
resolve: `gatsby-transformer-remark`,
options: {
// ...
},
},
#javascript #git #react #gatsby
1600544520
In this article, we will look at how we can add an “edit post” button, to your Gatsby blog. When this button is clicked it will take the user to your markdown file, on github/gitlab that was used to generate the blog post they are currently viewing.
Before we add the edit button to a Gatsby blog, let’s set up a simple Gatsby site using the Gatsby blog starter
. You can skip this step and add the button to an existing site.
npm -g install gatsby-cli
gatsby new my-blog-starter https://github.com/gatsbyjs/gatsby-starter-blog
If you don’t use the start above, you will need to make sure you have the gatsby-source-filesystem
plugin installed. To import our markdown files. Your gatsby-config.js
looks like this:
{
resolve: `gatsby-source-filesystem`,
options: {
path: `${__dirname}/content/blog`,
name: `blog`,
},
},
Then make sure you also have the gatsby-transformer-remark
plugin installed and it should be in your gatsby-config.js
like so:
{
resolve: `gatsby-transformer-remark`,
options: {
// ...
},
},
#javascript #git #react #gatsby
1641616950
Dans cet article, vous découvrirez la .append()
méthode en Python. Vous verrez également en quoi .append()
diffère des autres méthodes utilisées pour ajouter des éléments aux listes.
Commençons!
Un tableau en programmation est une collection ordonnée d'éléments, et tous les éléments doivent être du même type de données.
Cependant, contrairement à d'autres langages de programmation, les tableaux ne sont pas une structure de données intégrée à Python. Au lieu des tableaux traditionnels, Python utilise des listes.
Les listes sont essentiellement des tableaux dynamiques et sont l'une des structures de données les plus courantes et les plus puissantes de Python.
Vous pouvez les considérer comme des conteneurs commandés. Ils stockent et organisent ensemble des données similaires.
Les éléments stockés dans une liste peuvent être de n'importe quel type de données.
Il peut y avoir des listes d'entiers (nombres entiers), des listes de flottants (nombres à virgule flottante), des listes de chaînes (texte) et des listes de tout autre type de données Python intégré.
Bien qu'il soit possible pour les listes de ne contenir que des éléments du même type de données, elles sont plus flexibles que les tableaux traditionnels. Cela signifie qu'il peut y avoir une variété de types de données différents dans la même liste.
Les listes ont 0 ou plusieurs éléments, ce qui signifie qu'il peut également y avoir des listes vides. À l'intérieur d'une liste, il peut également y avoir des valeurs en double.
Les valeurs sont séparées par une virgule et placées entre crochets, []
.
Pour créer une nouvelle liste, donnez d'abord un nom à la liste. Ajoutez ensuite l'opérateur d'affectation ( =
) et une paire de crochets ouvrants et fermants. A l'intérieur des parenthèses, ajoutez les valeurs que la liste doit contenir.
#create a new list of names
names = ["Jimmy", "Timmy", "Kenny", "Lenny"]
#print the list to the console
print(names)
#output
#['Jimmy', 'Timmy', 'Kenny', 'Lenny']
Les listes maintiennent un ordre pour chaque article.
Chaque élément de la collection a son propre numéro d'index, que vous pouvez utiliser pour accéder à l'élément lui-même.
Les index en Python (et tout autre langage de programmation moderne) commencent à 0 et augmentent pour chaque élément de la liste.
Par exemple, la liste créée précédemment avait 4 valeurs :
names = ["Jimmy", "Timmy", "Kenny", "Lenny"]
La première valeur de la liste, "Jimmy", a un indice de 0.
La deuxième valeur de la liste, "Timmy", a un indice de 1.
La troisième valeur de la liste, "Kenny", a un indice de 2.
La quatrième valeur de la liste, "Lenny", a un indice de 3.
Pour accéder à un élément de la liste par son numéro d'index, écrivez d'abord le nom de la liste, puis entre crochets écrivez l'entier de l'index de l'élément.
Par exemple, si vous vouliez accéder à l'élément qui a un index de 2, vous feriez :
names = ["Jimmy", "Timmy", "Kenny", "Lenny"]
print(names[2])
#output
#Kenny
En Python, lorsque les objets sont mutables , cela signifie que leurs valeurs peuvent être modifiées une fois qu'ils ont été créés.
Les listes sont des objets modifiables, vous pouvez donc les mettre à jour et les modifier après leur création.
Les listes sont également dynamiques, ce qui signifie qu'elles peuvent augmenter et diminuer tout au long de la vie d'un programme.
Des éléments peuvent être supprimés d'une liste existante et de nouveaux éléments peuvent être ajoutés à une liste existante.
Il existe des méthodes intégrées pour ajouter et supprimer des éléments des listes.
Par exemple, pour add articles, il y a les .append()
, .insert()
et les .extend()
méthodes.
Pour supprimer des éléments, il existe les méthodes .remove()
, .pop()
et .pop(index)
.
.append()
méthode ?La .append()
méthode ajoute un élément supplémentaire à la fin d'une liste déjà existante.
La syntaxe générale ressemble à ceci :
list_name.append(item)
Décomposons-le :
list_name
est le nom que vous avez donné à la liste..append()
est la méthode de liste pour ajouter un élément à la fin de list_name
.item
est l'élément individuel spécifié que vous souhaitez ajouter.Lors de l'utilisation de .append()
, la liste d'origine est modifiée. Aucune nouvelle liste n'est créée.
Si vous souhaitez ajouter un nom supplémentaire à la liste créée précédemment, procédez comme suit :
names = ["Jimmy", "Timmy", "Kenny", "Lenny"]
#add the name Dylan to the end of the list
names.append("Dylan")
print(names)
#output
#['Jimmy', 'Timmy', 'Kenny', 'Lenny', 'Dylan']
.append()
et .insert()
?La différence entre les deux méthodes est qu'elle .append()
ajoute un élément à la fin d'une liste, alors qu'elle .insert()
insère et élément à une position spécifiée dans la liste.
Comme vous l'avez vu dans la section précédente, .append()
ajoutera l'élément que vous passez comme argument à la fonction toujours à la fin de la liste.
Si vous ne souhaitez pas simplement ajouter des éléments à la fin d'une liste, vous pouvez spécifier la position à laquelle vous souhaitez les ajouter avec .insert()
.
La syntaxe générale ressemble à ceci :
list_name.insert(position,item)
Décomposons-le :
list_name
est le nom de la liste..insert()
est la méthode de liste pour insérer un élément dans une liste.position
est le premier argument de la méthode. C'est toujours un entier - en particulier c'est le numéro d'index de la position où vous voulez que le nouvel élément soit placé.item
est le deuxième argument de la méthode. Ici, vous spécifiez le nouvel élément que vous souhaitez ajouter à la liste.Par exemple, supposons que vous disposiez de la liste suivante de langages de programmation :
programming_languages = ["JavaScript", "Java", "C++"]
print(programming_languages)
#output
#['JavaScript', 'Java', 'C++']
Si vous vouliez insérer "Python" au début de la liste, en tant que nouvel élément de la liste, vous utiliseriez la .insert()
méthode et spécifieriez la position comme 0
. (Rappelez-vous que la première valeur d'une liste a toujours un indice de 0.)
programming_languages = ["JavaScript", "Java", "C++"]
programming_languages.insert(0, "Python")
print(programming_languages)
#output
#['Python', 'JavaScript', 'Java', 'C++']
Si vous aviez plutôt voulu que "JavaScript" soit le premier élément de la liste, puis ajoutez "Python" comme nouvel élément, vous spécifieriez la position comme suit1
:
programming_languages = ["JavaScript", "Java", "C++"]
programming_languages.insert(1,"Python")
print(programming_languages)
#output
#['JavaScript', 'Python', 'Java', 'C++']
La .insert()
méthode vous donne un peu plus de flexibilité par rapport à la .append()
méthode qui ajoute uniquement un nouvel élément à la fin de la liste.
.append()
et .extend()
?Que faire si vous souhaitez ajouter plusieurs éléments à une liste à la fois, au lieu de les ajouter un à la fois ?
Vous pouvez utiliser la .append()
méthode pour ajouter plusieurs éléments à la fin d'une liste.
Supposons que vous ayez une liste qui ne contient que deux langages de programmation :
programming_languages = ["JavaScript", "Java"]
print(programming_languages)
#output
#['JavaScript', 'Java']
Vous souhaitez ensuite ajouter deux autres langues, à la fin.
Dans ce cas, vous passez une liste contenant les deux nouvelles valeurs que vous souhaitez ajouter, en argument à .append()
:
programming_languages = ["JavaScript", "Java"]
#add two new items to the end of the list
programming_languages.append(["Python","C++"])
print(programming_languages)
#output
#['JavaScript', 'Java', ['Python', 'C++']]
Si vous regardez de plus près la sortie ci-dessus, ['JavaScript', 'Java', ['Python', 'C++']]
vous verrez qu'une nouvelle liste a été ajoutée à la fin de la liste déjà existante.
Donc, .append()
ajoute une liste à l'intérieur d'une liste .
Les listes sont des objets, et lorsque vous utilisez .append()
pour ajouter une autre liste dans une liste, les nouveaux éléments seront ajoutés en tant qu'objet unique (élément).
Supposons que vous ayez déjà deux listes, comme ceci :
names = ["Jimmy", "Timmy"]
more_names = ["Kenny", "Lenny"]
Et si vous vouliez combiner le contenu des deux listes en une seule, en ajoutant le contenu de more_names
to names
?
Lorsque la .append()
méthode est utilisée à cette fin, une autre liste est créée à l'intérieur de names
:
names = ["Jimmy", "Timmy"]
more_names = ["Kenny", "Lenny"]
#add contents of more_names to names
names.append(more_names)
print(names)
#output
#['Jimmy', 'Timmy', ['Kenny', 'Lenny']]
Donc, .append()
ajoute les nouveaux éléments comme une autre liste, en ajoutant l'objet à la fin.
Pour réellement concaténer (ajouter) des listes et combiner tous les éléments d'une liste à une autre , vous devez utiliser la .extend()
méthode.
La syntaxe générale ressemble à ceci :
list_name.extend(iterable/other_list_name)
Décomposons-le :
list_name
est le nom de l'une des listes..extend()
est la méthode pour ajouter tout le contenu d'une liste à une autre.iterable
peut être n'importe quel itérable tel qu'une autre liste, par exemple, another_list_name
. Dans ce cas, another_list_name
est une liste qui sera concaténée avec list_name
, et son contenu sera ajouté un par un à la fin de list_name
, en tant qu'éléments séparés.Ainsi, en reprenant l'exemple précédent, lorsque .append()
est remplacé par .extend()
, la sortie ressemblera à ceci :
names = ["Jimmy", "Timmy"]
more_names = ["Kenny", "Lenny"]
names.extend(more_names)
print(names)
#output
#['Jimmy', 'Timmy', 'Kenny', 'Lenny']
Lorsque nous avons utilisé .extend()
, la names
liste s'est allongée et sa longueur a été augmentée de 2.
La façon dont cela .extend()
fonctionne est qu'il prend une liste (ou un autre itérable) comme argument, itère sur chaque élément, puis chaque élément de l'itérable est ajouté à la liste.
Il existe une autre différence entre .append()
et .extend()
.
Lorsque vous souhaitez ajouter une chaîne, comme vu précédemment, .append()
ajoutez l'élément entier et unique à la fin de la liste :
names = ["Jimmy", "Timmy", "Kenny", "Lenny"]
#add the name Dylan to the end of the list
names.append("Dylan")
print(names)
#output
#['Jimmy', 'Timmy', 'Kenny', 'Lenny', 'Dylan']
Si vous aviez .extend()
plutôt l' habitude d'ajouter une chaîne à la fin d'une liste, chaque caractère de la chaîne serait ajouté en tant qu'élément individuel à la liste.
C'est parce que les chaînes sont un itérable et .extend()
qu'elles itèrent sur l'argument itérable qui lui est transmis.
Ainsi, l'exemple ci-dessus ressemblerait à ceci :
names = ["Jimmy", "Timmy", "Kenny", "Lenny"]
#pass a string(iterable) to .extend()
names.extend("Dylan")
print(names)
#output
#['Jimmy', 'Timmy', 'Kenny', 'Lenny', 'D', 'y', 'l', 'a', 'n']
En résumé, la .append()
méthode est utilisée pour ajouter un élément à la fin d'une liste existante, sans créer de nouvelle liste.
Lorsqu'il est utilisé pour ajouter une liste à une autre liste, il crée une liste dans une liste.
Si vous souhaitez en savoir plus sur Python, consultez la certification Python de freeCodeCamp . Vous commencerez à apprendre de manière interactive et conviviale pour les débutants. Vous construirez également cinq projets à la fin pour mettre en pratique ce que vous avez appris.
Merci d'avoir lu et bon codage!
Link: https://www.freecodecamp.org/news/append-in-python-how-to-append-to-a-list-or-an-array/
1607523900
In this video, We have created a Tab design in HTML and CSS without using JavaScript. I have also provided HTML and CSS code on my website, you can visit my website by clicking given link.
Subscribe: https://www.youtube.com/@CodingLabYT/featured
Source Code :
HTML :
<!DOCTYPE html>
<html lang="en" dir="ltr">
<head>
<meta charset="UTF-8">
<!--<title> CSS Vertical Tabs </title>-->
<link rel="stylesheet" href="style.css">
<!-- Fontawesome CDN Link -->
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/5.15.2/css/all.min.css"/>
<meta name="viewport" content="width=device-width, initial-scale=1.0">
</head>
<body>
<div class="container">
<div class="topic">CSS Vertical Tabs.</div>
<div class="content">
<input type="radio" name="slider" checked id="home">
<input type="radio" name="slider" id="blog">
<input type="radio" name="slider" id="help">
<input type="radio" name="slider" id="code">
<input type="radio" name="slider" id="about">
<div class="list">
<label for="home" class="home">
<i class="fas fa-home"></i>
<span class="title">Home</span>
</label>
<label for="blog" class="blog">
<span class="icon"><i class="fas fa-blog"></i></span>
<span class="title">Blog</span>
</label>
<label for="help" class="help">
<span class="icon"><i class="far fa-envelope"></i></span>
<span class="title">Help</span>
</label>
<label for="code" class="code">
<span class="icon"><i class="fas fa-code"></i></span>
<span class="title">Code</span>
</label>
<label for="about" class="about">
<span class="icon"><i class="far fa-user"></i></span>
<span class="title">About</span>
</label>
<div class="slider"></div>
</div>
<div class="text-content">
<div class="home text">
<div class="title">Home Content</div>
<p>Lorem ipsum dolor sit amet, consectetur adipisicing elit. Quasi excepturi ducimus sequi dignissimos expedita tempore omnis quos cum, possimus, aspernatur esse nihil commodi est maiores dolorum rem iusto atque, beatae voluptas sit eligendi architecto dolorem temporibus. Non magnam ipsam, voluptas quasi nam dicta ut. Ad corrupti aliquid obcaecati alias, nemo veritatis porro nisi eius sequi dignissimos ea repellendus quibusdam minima ipsum animi quae, libero quisquam a! Laudantium iste est sapiente, ullam itaque odio iure laborum voluptatem quaerat tempore doloremque quam modi, atque minima enim saepe! Dolorem rerum minima incidunt, officia!</p>
</div>
<div class="blog text">
<div class="title">Blog Content</div>
<p>Lorem ipsum dolor sit amet, consectetur adipisicing elit. Alias tempora, unde reprehenderit incidunt excepturi blanditiis ullam dignissimos provident quam? Fugit, enim! Architecto ad officiis dignissimos ex quae iusto amet pariatur, ea eius aut velit, tempora magnam hic autem maiores unde corrupti tenetur delectus! Voluptatum praesentium labore consectetur ea qui illum illo distinctio, sunt, ipsam rerum optio quibusdam cum a? Aut facilis non fuga molestiae voluptatem omnis reprehenderit, dignissimos commodi repellat sapiente natus ipsam, ipsa distinctio. Ducimus repudiandae fuga aliquid, numquam.</p>
</div>
<div class="help text">
<div class="title">Help Content</div>
<p>Lorem ipsum dolor sit amet, consectetur adipisicing elit. Maiores error neque, officia excepturi dolores quis dolor, architecto iusto deleniti a soluta nostrum. Fuga reiciendis beatae, dicta voluptatem, vitae eligendi maxime accusamus. Amet totam aut odio velit cumque autem neque sequi provident mollitia, nisi sunt maiores facilis debitis in officiis asperiores saepe quo soluta laudantium ad non quisquam! Repellendus culpa necessitatibus aliquam quod mollitia perspiciatis ducimus doloribus perferendis autem, omnis, impedit, veniam qui dolorem? Ipsam nihil assumenda, sit ratione blanditiis eius aliquam libero iusto, dolorum aut perferendis modi laboriosam sint dolor.</p>
</div>
<div class="code text">
<div class="title">Code Content</div>
<p>Lorem ipsum dolor sit amet, consectetur adipisicing elit. Tempore magnam vitae inventore blanditiis nam tenetur voluptates doloribus error atque reprehenderit, necessitatibus minima incidunt a eius corrupti placeat, quasi similique deserunt, harum? Quia ut impedit ab earum expedita soluta repellat perferendis hic tempora inventore, accusantium porro consequuntur quisquam et assumenda distinctio dignissimos doloremque enim nemo delectus deserunt! Ullam perspiciatis quae aliquid animi quam amet deleniti, at dolorum tenetur, tempore laborum.</p>
</div>
<div class="about text">
<div class="title">About Content</div>
<p>Lorem ipsum dolor sit amet, consectetur adipisicing elit. Necessitatibus incidunt possimus quas ad, sit nam veniam illo ullam sapiente, aspernatur fugiat atque. Laboriosam libero voluptatum molestiae veniam earum quisquam, laudantium aperiam, eligendi dicta animi maxime sunt non nisi, ex, ipsa! Soluta ex, quibusdam voluptatem distinctio asperiores recusandae veritatis optio dolorem illo nesciunt quos ullam, dicta numquam ipsam cumque sed. Blanditiis omnis placeat, enim sit dicta eligendi voluptatibus laborum consectetur repudiandae tempora numquam molestiae rerum mollitia nemo. Velit perspiciatis, nesciunt, quo illo quas error debitis molestiae et sapiente neque tempore natus?</p>
</div>
</div>
</div>
</div>
</body>
</html>
CSS :
@import url('https://fonts.googleapis.com/css2?family=Poppins:wght@200;300;400;500;600;700&display=swap');
*{
margin: 0;
padding: 0;
box-sizing: border-box;
font-family: 'Poppins', sans-serif;
}
body{
height: 100vh;
display: flex;
align-items: center;
justify-content: center;
background: #dad3f8;
}
::selection{
background: #6d50e2;
color: #fff;
}
.container{
max-width: 950px;
width: 100%;
padding: 40px 50px 40px 40px;
background: #fff;
margin: 0 20px;
border-radius: 12px;
box-shadow: 0 5px 10px rgba(0, 0, 0, 0.2);
}
.container .topic{
font-size: 30px;
font-weight: 500;
margin-bottom: 20px;
}
.content{
display: flex;
align-items: center;
justify-content: space-between;
}
.content .list{
display: flex;
flex-direction: column;
width: 20%;
margin-right: 50px;
position: relative;
}
.content .list label{
height: 60px;
font-size: 22px;
font-weight: 500;
line-height: 60px;
cursor: pointer;
padding-left: 25px;
transition: all 0.5s ease;
color: #333;
z-index: 12;
}
#home:checked ~ .list label.home,
#blog:checked ~ .list label.blog,
#help:checked ~ .list label.help,
#code:checked ~ .list label.code,
#about:checked ~ .list label.about{
color: #fff;
}
.content .list label:hover{
color: #6d50e2;
}
.content .slider{
position: absolute;
left: 0;
top: 0;
height: 60px;
width: 100%;
border-radius: 12px;
background: #6d50e2;
transition: all 0.4s ease;
}
#home:checked ~ .list .slider{
top: 0;
}
#blog:checked ~ .list .slider{
top: 60px;
}
#help:checked ~ .list .slider{
top: 120px;
}
#code:checked ~ .list .slider{
top: 180px;
}
#about:checked ~ .list .slider{
top: 240px;
}
.content .text-content{
width: 80%;
height: 100%;
}
.content .text{
display: none;
}
.content .text .title{
font-size: 25px;
margin-bottom: 10px;
font-weight: 500;
}
.content .text p{
text-align: justify;
}
.content .text-content .home{
display: block;
}
#home:checked ~ .text-content .home,
#blog:checked ~ .text-content .blog,
#help:checked ~ .text-content .help,
#code:checked ~ .text-content .code,
#about:checked ~ .text-content .about{
display: block;
}
#blog:checked ~ .text-content .home,
#help:checked ~ .text-content .home,
#code:checked ~ .text-content .home,
#about:checked ~ .text-content .home{
display: none;
}
.content input{
display: none;
}
#javascript #html #css
1666082925
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.
Let's get started!
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.
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.
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.
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
:
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()
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()
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()
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.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.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:
TYPECODE | C TYPE | PYTHON TYPE | SIZE |
---|---|---|---|
'b' | signed char | int | 1 |
'B' | unsigned char | int | 1 |
'u' | wchar_t | Unicode character | 2 |
'h' | signed short | int | 2 |
'H' | unsigned short | int | 2 |
'i' | signed int | int | 2 |
'I' | unsigned int | int | 2 |
'l' | signed long | int | 4 |
'L' | unsigned long | int | 4 |
'q' | signed long long | int | 8 |
'Q' | unsigned long long | int | 8 |
'f' | float | float | 4 |
'd' | double | float | 8 |
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:
import array as arr
.numbers
array.arr.array()
because of import array as arr
.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.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.
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
.
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
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
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
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])
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.
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])
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])
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])
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
1645534030
Given two user input matrix. Our task is to display the addition of two matrix. In these problem we use nested List comprehensive.
matrix multiplication in python user input
Step1: input two matrix.
Step 2: nested for loops to iterate through each row and each column.
Step 3: take one resultant matrix which is initially contains all 0. Then we multiply each row elements of first matrix with each elements of second matrix, then add all multiplied value. That is the value of resultant matrix.
# Program to multiply two matrices
A=[]
n=int(input("Enter N for N x N matrix: "))
print("Enter the element ::>")
for i in range(n):
row=[] #temporary list to store the row
for j in range(n):
row.append(int(input())) #add the input to row list
A.append(row) #add the row to the list
print(A)
# [[1, 2, 3], [4, 5, 6], [7, 8, 9]]
#Display the 2D array
print("Display Array In Matrix Form")
for i in range(n):
for j in range(n):
print(A[i][j], end=" ")
print() #new line
B=[]
n=int(input("Enter N for N x N matrix : ")) #3 here
#use list for storing 2D array
#get the user input and store it in list (here IN : 1 to 9)
print("Enter the element ::>")
for i in range (n):
row=[] #temporary list to store the row
for j in range(n):
row.append(int(input())) #add the input to row list
B.append(row) #add the row to the list
print(B)
# [[1, 2, 3], [4, 5, 6], [7, 8, 9]]
#Display the 2D array
print("Display Array In Matrix Form")
for i in range(n):
for j in range(n):
print(B[i][j], end=" ")
print()
result = [[0,0,0], [0,0,0], [0,0,0]]
for i in range(len(A)):
for j in range(len(B[0])):
for k in range(len(B)):
result[i][j] += A[i][k] * B[k][j]
print("The Resultant Matrix Is ::>")
for r in result:
print(r)
Enter N for N x N matrix: 3
Enter the element ::>
2
1
4
2
1
2
3
4
3
[[2, 1, 4], [2, 1, 2], [3, 4, 3]]
Display Array In Matrix Form
2 1 4
2 1 2
3 4 3
Enter N for N x N matrix : 3
Enter the element ::>
1
2
3
4
5
6
7
8
9
[[1, 2, 3], [4, 5, 6], [7, 8, 9]]
Display Array In Matrix Form
1 2 3
4 5 6
7 8 9
The Resultant Matrix Is ::>
[34, 41, 48]
[20, 25, 30]
[40, 50, 60]
https://www.pakainfo.com/python-program-multiplication-of-two-matrix-from-user-input/