1645499493
Vous avez confiance en vos connaissances React ? Mettez-le à l'épreuve !
J'ai sélectionné toutes les principales questions que vous devez connaître en tant que développeur React en 2022, que vous passiez un entretien pour un poste embauché ou non.
Ces questions couvrent tout, des concepts de base de React à une compréhension pratique du moment où vous devez utiliser certaines fonctionnalités.
Pour tirer le meilleur parti de ce guide, assurez-vous d'essayer de répondre vous-même à chaque question avant de regarder les réponses.
Commençons!
Vous voulez que la ressource n°1 devienne un développeur React embauché ? Devenez un pro React en 4-5 semaines avec le React Bootcamp .
React est une bibliothèque JavaScript , pas un framework.
Nous utilisons React car il nous donne toute la puissance de JavaScript, mais avec des fonctionnalités intégrées qui améliorent la façon dont nous construisons et pensons à la création d'applications.
Crédit supplémentaire : Il existe des frameworks dans React qui vous donnent tout ce dont vous avez besoin pour créer une application (avec peu ou pas de bibliothèques tierces), comme Next.js et Gatsby.
React a été créé pour créer des applications d'une seule page en particulier, mais vous pouvez tout créer, des sites statiques aux applications mobiles avec les mêmes concepts React.
JSX est un moyen de créer des interfaces utilisateur React qui utilisent la syntaxe simple de HTML, mais ajoute la fonctionnalité et la nature dynamique de JavaScript.
En bref, c'est HTML + JavaScript pour structurer nos applications React .
Bien que JSX ressemble à du HTML, sous le capot, il s'agit en fait d' appels de fonction JavaScript .
Si vous écrivez a div
dans JSX, c'est en fait l'équivalent d'appeler React.createElement()
.
Nous pouvons construire nos interfaces utilisateur en appelant manuellement React.createElement
, mais au fur et à mesure que nous ajoutons des éléments, il devient de plus en plus difficile de lire la structure que nous avons construite.
Le navigateur ne peut pas comprendre JSX lui-même, nous utilisons donc souvent un compilateur JavaScript appelé Babel pour convertir ce qui ressemble à du HTML en appels de fonction JavaScript que le navigateur peut comprendre.
Il existe 2 manières principales de transmettre des données aux composants React :
Les props sont des données transmises depuis le parent immédiat d'un composant. Les accessoires sont déclarés sur le composant enfant, peuvent porter n'importe quel nom et accepter n'importe quelle valeur valide.
function Blog() {
const post = { title: "My Blog Post!" };
return <BlogPost post={post} />;
}
Les accessoires sont consommés dans le composant enfant. Les accessoires sont toujours disponibles dans l'enfant en tant que propriétés sur un objet .
function BlogPost(props) {
return <h1>{props.post.title}</h1>
}
Étant donné que les accessoires sont des propriétés d'objet simples, ils peuvent être déstructurés pour un accès plus immédiat.
function BlogPost({ post }) {
return <h1>{post.title}</h1>
}
Le contexte correspond aux données transmises d'un fournisseur de contexte à tout composant qui utilise le contexte.
Le contexte nous permet d'accéder aux données n'importe où dans notre application (si le fournisseur est passé autour de l'ensemble de l'arborescence des composants), sans utiliser d'accessoires.
Les données de contexte sont transmises sur l' value
accessoire à l'aide du Context.Provider
composant. Il peut être consommé à l'aide du composant Context.Consumer ou du useContext
hook.
import { createContext, useContext } from 'react';
const PostContext = createContext()
function App() {
const post = { title: "My Blog Post!" };
return (
<PostContext.Provider value={post}>
<Blog />
</PostContext.Provider>
);
}
function Blog() {
return <BlogPost />
}
function BlogPost() {
const post = useContext(PostContext)
return <h1>{post.title}</h1>
}
Les états sont des valeurs que nous pouvons lire et mettre à jour dans nos composants React.
Les props sont des valeurs qui sont transmises aux composants React et sont en lecture seule (elles ne doivent pas être mises à jour).
Vous pouvez considérer les accessoires comme étant similaires aux arguments d'une fonction qui existent en dehors de nos composants, tandis que l'état sont des valeurs qui changent avec le temps, mais qui existent et sont déclarées à l'intérieur de nos composants.
L'état et les accessoires sont similaires en ce sens que leurs modifications entraînent un nouveau rendu des composants dans lesquels ils existent.
Les fragments React sont une fonctionnalité spéciale de React qui vous permet d'écrire des éléments ou des composants enfants de groupe sans créer de nœud réel dans le DOM.
La syntaxe du fragment ressemble à un ensemble vide de balises <></>
ou sont des balises étiquetées React.Fragment
.
En termes plus simples, nous devons parfois placer plusieurs éléments React sous un seul parent, mais nous ne voulons pas utiliser un élément HTML générique comme un div
.
Si vous écrivez un tableau, par exemple, ce serait un code HTML invalide :
function Table() {
return (
<table>
<tr>
<Columns />
</tr>
</table>
);
}
function Columns() {
return (
<div>
<td>Column 1</td>
<td>Column 2</td>
</div>
);
}
Nous pourrions éviter ce problème en utilisant un fragment au lieu d'un div
élément dans notre Columns
composant.
function Columns() {
return (
<>
<td>Column 1</td>
<td>Column 2</td>
</>
);
}
Une autre raison de choisir un fragment est que parfois l'ajout d'un élément HTML supplémentaire peut changer la façon dont nos styles CSS sont appliqués.
Les clés sont une valeur unique que nous devons transmettre à la key
prop lorsque nous utilisons la .map()
fonction pour boucler sur un élément ou un composant.
Si nous mappons sur un élément, cela ressemblerait à ceci :
posts.map(post => <li key={post.id}>{post.title}</li>)
Ou comme ceci si nous mappons sur un composant :
posts.map(post => <li key={post.id}>{post.title}</li>)
Et dans les deux cas, nous devons ajouter une clé qui est une valeur unique, sinon React nous avertira.
Pourquoi? Parce que les clés indiquent à React quel élément ou composant est lequel dans une liste .
Sinon, si nous devions essayer de changer les éléments de cette liste en en insérant plus ou en les modifiant d'une manière ou d'une autre, React ne connaîtrait pas l'ordre dans lequel les mettre.
En effet, React s'occupe de toutes les activités de mise à jour du DOM pour nous (en utilisant un DOM virtuel), mais des clés sont nécessaires pour que React le mette à jour correctement .
Une référence est une référence à un élément DOM dans React.
Les références sont créées à l'aide du useRef
crochet et peuvent être immédiatement placées dans une variable.
Cette variable est ensuite transmise à un élément React donné (pas un composant) pour obtenir une référence à l'élément DOM sous-jacent (c'est-à-dire div, span, etc.).
L'élément lui-même et ses propriétés sont maintenant disponibles sur la propriété .current de la ref.
import { useRef } from 'react'
function MyComponent() {
const ref = useRef();
useEffect(() => {
console.log(ref.current) // reference to div element
}, [])
return <div ref={ref} />
}
Les références sont souvent appelées "trappe de sortie" pour pouvoir travailler directement avec un élément DOM. Ils nous permettent d'effectuer certaines opérations qui ne peuvent pas être effectuées via React autrement, comme effacer ou focaliser une entrée.
Le useEffect
crochet est utilisé pour effectuer des effets secondaires dans nos composants React.
Les effets secondaires sont des opérations qui sont effectuées avec le "monde extérieur" ou quelque chose qui existe en dehors du contexte de notre application React.
Certains exemples d'effets secondaires incluent l'envoi d'une requête GET ou POST à un point de terminaison d'API externe ou l'utilisation d'une API de navigateur telle que window.navigator
ou document.getElementById()
.
Nous ne pouvons pas effectuer de telles opérations directement dans le corps de notre composant React. useEffect
nous donne une fonction dans laquelle effectuer des effets secondaires et un tableau de dépendances qui répertorie toutes les valeurs externes sur lesquelles la fonction s'appuie.
Si une valeur dans le tableau des dépendances change, la fonction d'effet s'exécute à nouveau.
Redux est probablement la bibliothèque d'état globale tierce la plus couramment utilisée pour React, mais vous pouvez remplacer le mot "Redux" par n'importe quelle bibliothèque d'état globale pour React.
Le contexte de réaction est un moyen de fournir et de consommer des données dans notre application sans utiliser d'accessoires .
Le contexte React nous aide à éviter le problème du " forage d'accessoires ", c'est-à-dire lorsque vous transmettez des données avec des accessoires à travers des composants qui n'en ont pas besoin.
Au lieu de cela, avec le contexte, nous pouvons consommer les données exactement dans le composant qui en a besoin .
Bien que nous n'utilisions Context que pour obtenir ou "lire" des valeurs globalement dans notre application, Redux et d'autres bibliothèques d'état tierces nous permettent à la fois de lire et de mettre à jour state .
Context ne remplace pas une bibliothèque d'état tierce comme Redux, car elle n'est pas conçue pour les mises à jour d'état . En effet, chaque fois que la valeur fournie sur Context change, tous ses enfants seront restitués, ce qui peut nuire aux performances.
Les crochets useCallback
et useMemo
existent pour améliorer les performances de nos composants.
useCallback
est d'empêcher les fonctions déclarées dans le corps des composants de fonction d'être recréées à chaque rendu.
Cela peut entraîner des problèmes de performances inutiles, en particulier pour les fonctions de rappel transmises aux composants enfants.
useMemo
, d'autre part, mémorise une opération coûteuse que nous lui donnons.
La mémorisation est un terme technique désignant les fonctions capables de "se souvenir" des valeurs passées qu'elles ont calculées si leurs arguments n'ont pas changé. Si tel est le cas, la fonction renvoie la valeur "mémorisée".
En d'autres termes, on peut avoir un calcul qui demande une quantité importante de ressources de calcul et on souhaite qu'il soit effectué avec le moins de parcimonie possible.
Dans ce cas, nous utilisons le useMemo
crochet, qui diffère du useCallback
crochet en ce qu'il renvoie une valeur, pas une fonction.
Si vous souhaitez devenir un développeur React prêt à travailler de la manière la plus simple possible, consultez le React Bootcamp .
Il vous apportera toutes les compétences nécessaires pour :
Link: https://www.freecodecamp.org/news/react-interview-questions-to-know/
1645499493
Vous avez confiance en vos connaissances React ? Mettez-le à l'épreuve !
J'ai sélectionné toutes les principales questions que vous devez connaître en tant que développeur React en 2022, que vous passiez un entretien pour un poste embauché ou non.
Ces questions couvrent tout, des concepts de base de React à une compréhension pratique du moment où vous devez utiliser certaines fonctionnalités.
Pour tirer le meilleur parti de ce guide, assurez-vous d'essayer de répondre vous-même à chaque question avant de regarder les réponses.
Commençons!
Vous voulez que la ressource n°1 devienne un développeur React embauché ? Devenez un pro React en 4-5 semaines avec le React Bootcamp .
React est une bibliothèque JavaScript , pas un framework.
Nous utilisons React car il nous donne toute la puissance de JavaScript, mais avec des fonctionnalités intégrées qui améliorent la façon dont nous construisons et pensons à la création d'applications.
Crédit supplémentaire : Il existe des frameworks dans React qui vous donnent tout ce dont vous avez besoin pour créer une application (avec peu ou pas de bibliothèques tierces), comme Next.js et Gatsby.
React a été créé pour créer des applications d'une seule page en particulier, mais vous pouvez tout créer, des sites statiques aux applications mobiles avec les mêmes concepts React.
JSX est un moyen de créer des interfaces utilisateur React qui utilisent la syntaxe simple de HTML, mais ajoute la fonctionnalité et la nature dynamique de JavaScript.
En bref, c'est HTML + JavaScript pour structurer nos applications React .
Bien que JSX ressemble à du HTML, sous le capot, il s'agit en fait d' appels de fonction JavaScript .
Si vous écrivez a div
dans JSX, c'est en fait l'équivalent d'appeler React.createElement()
.
Nous pouvons construire nos interfaces utilisateur en appelant manuellement React.createElement
, mais au fur et à mesure que nous ajoutons des éléments, il devient de plus en plus difficile de lire la structure que nous avons construite.
Le navigateur ne peut pas comprendre JSX lui-même, nous utilisons donc souvent un compilateur JavaScript appelé Babel pour convertir ce qui ressemble à du HTML en appels de fonction JavaScript que le navigateur peut comprendre.
Il existe 2 manières principales de transmettre des données aux composants React :
Les props sont des données transmises depuis le parent immédiat d'un composant. Les accessoires sont déclarés sur le composant enfant, peuvent porter n'importe quel nom et accepter n'importe quelle valeur valide.
function Blog() {
const post = { title: "My Blog Post!" };
return <BlogPost post={post} />;
}
Les accessoires sont consommés dans le composant enfant. Les accessoires sont toujours disponibles dans l'enfant en tant que propriétés sur un objet .
function BlogPost(props) {
return <h1>{props.post.title}</h1>
}
Étant donné que les accessoires sont des propriétés d'objet simples, ils peuvent être déstructurés pour un accès plus immédiat.
function BlogPost({ post }) {
return <h1>{post.title}</h1>
}
Le contexte correspond aux données transmises d'un fournisseur de contexte à tout composant qui utilise le contexte.
Le contexte nous permet d'accéder aux données n'importe où dans notre application (si le fournisseur est passé autour de l'ensemble de l'arborescence des composants), sans utiliser d'accessoires.
Les données de contexte sont transmises sur l' value
accessoire à l'aide du Context.Provider
composant. Il peut être consommé à l'aide du composant Context.Consumer ou du useContext
hook.
import { createContext, useContext } from 'react';
const PostContext = createContext()
function App() {
const post = { title: "My Blog Post!" };
return (
<PostContext.Provider value={post}>
<Blog />
</PostContext.Provider>
);
}
function Blog() {
return <BlogPost />
}
function BlogPost() {
const post = useContext(PostContext)
return <h1>{post.title}</h1>
}
Les états sont des valeurs que nous pouvons lire et mettre à jour dans nos composants React.
Les props sont des valeurs qui sont transmises aux composants React et sont en lecture seule (elles ne doivent pas être mises à jour).
Vous pouvez considérer les accessoires comme étant similaires aux arguments d'une fonction qui existent en dehors de nos composants, tandis que l'état sont des valeurs qui changent avec le temps, mais qui existent et sont déclarées à l'intérieur de nos composants.
L'état et les accessoires sont similaires en ce sens que leurs modifications entraînent un nouveau rendu des composants dans lesquels ils existent.
Les fragments React sont une fonctionnalité spéciale de React qui vous permet d'écrire des éléments ou des composants enfants de groupe sans créer de nœud réel dans le DOM.
La syntaxe du fragment ressemble à un ensemble vide de balises <></>
ou sont des balises étiquetées React.Fragment
.
En termes plus simples, nous devons parfois placer plusieurs éléments React sous un seul parent, mais nous ne voulons pas utiliser un élément HTML générique comme un div
.
Si vous écrivez un tableau, par exemple, ce serait un code HTML invalide :
function Table() {
return (
<table>
<tr>
<Columns />
</tr>
</table>
);
}
function Columns() {
return (
<div>
<td>Column 1</td>
<td>Column 2</td>
</div>
);
}
Nous pourrions éviter ce problème en utilisant un fragment au lieu d'un div
élément dans notre Columns
composant.
function Columns() {
return (
<>
<td>Column 1</td>
<td>Column 2</td>
</>
);
}
Une autre raison de choisir un fragment est que parfois l'ajout d'un élément HTML supplémentaire peut changer la façon dont nos styles CSS sont appliqués.
Les clés sont une valeur unique que nous devons transmettre à la key
prop lorsque nous utilisons la .map()
fonction pour boucler sur un élément ou un composant.
Si nous mappons sur un élément, cela ressemblerait à ceci :
posts.map(post => <li key={post.id}>{post.title}</li>)
Ou comme ceci si nous mappons sur un composant :
posts.map(post => <li key={post.id}>{post.title}</li>)
Et dans les deux cas, nous devons ajouter une clé qui est une valeur unique, sinon React nous avertira.
Pourquoi? Parce que les clés indiquent à React quel élément ou composant est lequel dans une liste .
Sinon, si nous devions essayer de changer les éléments de cette liste en en insérant plus ou en les modifiant d'une manière ou d'une autre, React ne connaîtrait pas l'ordre dans lequel les mettre.
En effet, React s'occupe de toutes les activités de mise à jour du DOM pour nous (en utilisant un DOM virtuel), mais des clés sont nécessaires pour que React le mette à jour correctement .
Une référence est une référence à un élément DOM dans React.
Les références sont créées à l'aide du useRef
crochet et peuvent être immédiatement placées dans une variable.
Cette variable est ensuite transmise à un élément React donné (pas un composant) pour obtenir une référence à l'élément DOM sous-jacent (c'est-à-dire div, span, etc.).
L'élément lui-même et ses propriétés sont maintenant disponibles sur la propriété .current de la ref.
import { useRef } from 'react'
function MyComponent() {
const ref = useRef();
useEffect(() => {
console.log(ref.current) // reference to div element
}, [])
return <div ref={ref} />
}
Les références sont souvent appelées "trappe de sortie" pour pouvoir travailler directement avec un élément DOM. Ils nous permettent d'effectuer certaines opérations qui ne peuvent pas être effectuées via React autrement, comme effacer ou focaliser une entrée.
Le useEffect
crochet est utilisé pour effectuer des effets secondaires dans nos composants React.
Les effets secondaires sont des opérations qui sont effectuées avec le "monde extérieur" ou quelque chose qui existe en dehors du contexte de notre application React.
Certains exemples d'effets secondaires incluent l'envoi d'une requête GET ou POST à un point de terminaison d'API externe ou l'utilisation d'une API de navigateur telle que window.navigator
ou document.getElementById()
.
Nous ne pouvons pas effectuer de telles opérations directement dans le corps de notre composant React. useEffect
nous donne une fonction dans laquelle effectuer des effets secondaires et un tableau de dépendances qui répertorie toutes les valeurs externes sur lesquelles la fonction s'appuie.
Si une valeur dans le tableau des dépendances change, la fonction d'effet s'exécute à nouveau.
Redux est probablement la bibliothèque d'état globale tierce la plus couramment utilisée pour React, mais vous pouvez remplacer le mot "Redux" par n'importe quelle bibliothèque d'état globale pour React.
Le contexte de réaction est un moyen de fournir et de consommer des données dans notre application sans utiliser d'accessoires .
Le contexte React nous aide à éviter le problème du " forage d'accessoires ", c'est-à-dire lorsque vous transmettez des données avec des accessoires à travers des composants qui n'en ont pas besoin.
Au lieu de cela, avec le contexte, nous pouvons consommer les données exactement dans le composant qui en a besoin .
Bien que nous n'utilisions Context que pour obtenir ou "lire" des valeurs globalement dans notre application, Redux et d'autres bibliothèques d'état tierces nous permettent à la fois de lire et de mettre à jour state .
Context ne remplace pas une bibliothèque d'état tierce comme Redux, car elle n'est pas conçue pour les mises à jour d'état . En effet, chaque fois que la valeur fournie sur Context change, tous ses enfants seront restitués, ce qui peut nuire aux performances.
Les crochets useCallback
et useMemo
existent pour améliorer les performances de nos composants.
useCallback
est d'empêcher les fonctions déclarées dans le corps des composants de fonction d'être recréées à chaque rendu.
Cela peut entraîner des problèmes de performances inutiles, en particulier pour les fonctions de rappel transmises aux composants enfants.
useMemo
, d'autre part, mémorise une opération coûteuse que nous lui donnons.
La mémorisation est un terme technique désignant les fonctions capables de "se souvenir" des valeurs passées qu'elles ont calculées si leurs arguments n'ont pas changé. Si tel est le cas, la fonction renvoie la valeur "mémorisée".
En d'autres termes, on peut avoir un calcul qui demande une quantité importante de ressources de calcul et on souhaite qu'il soit effectué avec le moins de parcimonie possible.
Dans ce cas, nous utilisons le useMemo
crochet, qui diffère du useCallback
crochet en ce qu'il renvoie une valeur, pas une fonction.
Si vous souhaitez devenir un développeur React prêt à travailler de la manière la plus simple possible, consultez le React Bootcamp .
Il vous apportera toutes les compétences nécessaires pour :
Link: https://www.freecodecamp.org/news/react-interview-questions-to-know/
1595098800
Android Interview Questions and Answers from Beginner to Advanced level
DataFlair is committed to provide you all the resources to make you an android professional. We started with android tutorials along with practicals, then we published Real-time android projects along with source code. Now, we come up with frequently asked android interview questions, which will help you in showing expertise in your next interview.
Android – one of the hottest technologies, which is having a bright future. Get ready to crack your next interview with the following android interview questions. These interview questions start with basic and cover deep concepts along with advanced topics.
1. What is Android?
Android is an open-source mobile operating system that is based on the modified versions of Linux kernel. Though it was mainly designed for smartphones, now it is being used for Tablets, Televisions, Smartwatches, and other Android wearables.
2. Who is the inventor of Android Technology?
The inventors of Android Technology are- Andry Rubin, Nick Sears, and Rich Miner.
3. What is the latest version of Android?
The latest version of Android is Android 10.0, known as Android Q. The upcoming major Android release is Android 11, which is the 18th version of Android. [Note: Keep checking the versions, it is as of June 2020.]
4. How many Android versions can you recall right now?
Till now, there are 17 versions of Android, which have their names in alphabetical order. The 18th version of Android is also going to come later this year. The versions of Android are here:
5. Explain the Android Architecture with its components.
This is a popular android developer interview question
Android Architecture consists of 5 components that are-
a. Linux Kernel: It is the foundation of the Android Architecture that resides at the lowest level. It provides the level of abstraction for hardware devices and upper layer components. Linux Kernel also provides various important hardware drivers that act as software interfaces for hardwares like camera, bluetooth, etc.
b. Native Libraries: These are the libraries for Android that are written in C/C++. These libraries are useful to build many core services like ART and HAL. It provides support for core features.
c. Android Runtime: It is an Android Runtime Environment. Android Operating System uses it during the execution of the app. It performs the translation of the application bytecode into the native instructions. The runtime environment of the device then executes these native instructions.
d. Application Framework: Application Framework provides many java classes and interfaces for app development. And it also provides various high-level services. This complete Application framework makes use of Java.
e. Applications: This is the topmost layer of Android Architecture. It provides applications for the end-user, so they can use the android device and compute the tasks.
6. What are the services that the Application framework provides?
The Android application framework has the following key services-
a. Activity Manager: It uses testing and debugging methods.
b. Content provider: It provides the data from application to other layers.
c. Resource Manager: This provides users access to resources.
d. Notification Manager: This gives notification to the users regarding actions taking place in the background.
e. View System: It is the base class for widgets, and it is also responsible for event handling.
7. What are the important features of Linux Kernel?
The important features of the Linux Kernel are as follows:
a. Power Management: Linux Kernel does power management to enhance and improve the battery life of the device.
b. Memory Management: It is useful for the maximum utilization of the available memory of the device.
c. Device Management: It includes managing all the hardware device drivers. It maximizes the utilization of the available resources.
d. Security: It ensures that no application has any such permission that it affects any other application in order to maintain security.
e. Multi-tasking: Multi-tasking provides the users the ease of doing multiple tasks at the same time.
8. What are the building blocks of an Android Application?
This is a popular android interview question for freshers.
The main components of any Android application are- Activity, Services, Content Provider, and Broadcast Receiver. You can understand them as follows:
a. Activity- It is a class that acts as the entry point representing a single screen to the user. It is like a window to show the user interface.
b. Services- Services are the longest-running component that runs in the background.
c. Content Provider- The content provider is an essential component that allows apps to share data between themselves.
d. Broadcast receivers- Broadcast receiver is another most crucial application component. It helps the apps to receive and respond to broadcast messages from the system or some other application.
9. What are the important components of Android Application?
The Components of Android application are listed below:
10. What are the widgets?
Widgets are the variations of Broadcast receivers. They are an important part of home screen customization. They often display some data and also allow users to perform actions on them. Mostly they display the app icon on the screen.
11. Can you name some types of widgets?
Mentioned below are the types of widgets-
a. Informative Widgets: These widgets show some important information. Like, the clock widget or a weather widget.
b. Collective Widgets: They are the collection of some types of elements. For example, a music widget that lets us change, skip, or forward the song.
c. Control Widgets: These widgets help us control the actions within the application through it. Like an email widget that helps check the recent mails.
d. Hybrid Widgets: Hybrid widgets are those that consist of at least two or more types of widgets.
12. What are Intents?
Intents are an important part of Android Applications. They enable communication between components of the same application as well as separate applications. The Intent signals the Android system about a certain event that has occurred.
13. Explain the types of intents briefly?
Intent is of three types that are-
a. Implicit Intents: Implicit intents are those in which there is no description of the component name but only the action.
b. Explicit Intents: In explicit intents, the target component is present by declaring the name of the component.
c. Pending Intents: These are those intents that act as a shield over the Intent objects. It covers the intent objects and grants permission to the external app components to access them.
14. What is a View?
A view is an important building block that helps in designing the user interface of the application. It can be a rectangular box or a circular shape, for example, Text View, Edit Text, Buttons, etc. Views occupy a certain area of the screen, and it is also responsible for event handling. A view is the superclass of all the graphical user interface components.
15. What do you understand by View Group?
It is the subclass of the ViewClass. It gives an invisible container to hold layouts or views. You can understand view groups as special views that are capable of holding other views, that are Child View.
16. What do you understand about Shared Preferences?
It is a simple mechanism for data storage in Android. In this, there is no need to create files, and using APIs, it stores the data in XML files. It stores the data in the pair of key-values. SharedPreferences class lets the user save the values and retrieve them when required. Using SharedPreferences we can save primitive data like- boolean, float, integer, string and long.
17. What is a Notification?
A notification is just like a message that shows up outside the Application UI to provide reminders to the users. They remind the user about a message received, or some other timely information from the app.
18. Give names of Notification types.
There are three types of notifications namely-
a. Toast Notification- This notification is the one that fades away sometime after it pops up.
b. Status Notification- This notification stays till the user takes some action on it.
c. Dialog Notification- This notification is the result of an Active Activity.
19. What are fragments?
A fragment is a part of the complete user interface. These are present in Activity, and an activity can have one or more fragments at the same time. We can reuse a fragment in multiple activities as well.
20. What are the types of fragments?
There are three types of fragments that are: Single Fragment, List Fragment, Fragment Transactions.
21. What are Layout XML files?
Layout XML files contain the structure for the user interface of the application. The XML file also contains various different layouts and views, and they also specify various GUI components that are there in Activity or fragments.
22. What are Resources in Android Application?
The resources in Android Apps defines images, texts, strings, colors, etc. Everything in resources directory is referenced in the source code of the app so that we can use them.
23. Can you develop Android Apps with languages other than Java? If so, name some.
Yes, there are many languages that we can work with, for the development of Android Applications. To name some, I would say Java, Python, C, C++, Kotlin, C#, Corona/LUA.
24. What are the states of the Activity Lifecycle?
Activity lifecycle has the following four stages-
a. Running State: As soon as the activity starts, it is the first state.
b. Paused State: When some other activity starts without closing the previous one, the running activity turns into the Paused state.
c. Resume State: When the activity opens again after being in pause state, it comes into the Resume State.
d. Stopped State: When the user closes the application or stops using it, the activity goes to the Stopped state.
25. What are some methods of Activity?
The methods of Activity are as follows:
26. How can you launch an activity in Android?
We launch an activity using Intents. For this we need to use intent as follows:
27. What is the service lifecycle?
There are two states of a service that are-
a. Started State: This is when the service starts its execution. A Services come in start state only through the startService() method.
b. Bounded State: A service is in the bounded state when it calls the method bindService().
28. What are some methods of Services?
The methods of service are as follows-
29. What are the types of Broadcast?
Broadcasts are of two types that are-
a. Ordered Broadcast: Ordered broadcasts are Synchronous and work in a proper order. It decides the order by using the priority assigned to the broadcasts.
b. Normal Broadcast: These are asynchronous and unordered. They are more efficient as they run unorderly and all at once. But, they lack full utilization of the results.
30. What are useful impotent folders in Android?
The impotent folders in an Android application are-
31. What are the important files for Android Application when working on Android Studio?
This is an important android studio interview question
There are following three files that we need to work on for an application to work-
a. The AndroidManifest.xml file: It has all the information about the application.
b. The MainActivity.java file: It is the app file that actually gets converted to the dalvik executable and runs the application. It is written in java.
c. The Activity_main.xml file: It is the layout file that is available in the res/layout directory. It is another mostly used file while developing the application.
32. Which database do you use for Android Application development?
The database that we use for Android Applications is SQLite. It is because SQLite is lightweight and specially developed for Android Apps. SQLite works the same way as SQL using the same commands.
33. Tell us some features of Android OS.
The best features of Android include-
34. Why did you learn Android development?
Learning Android Studio is a good idea because of the following-
35. What are the different ways of storage supported in Android?
The various storage ways supported in Android are as follows:
36. What are layouts?
Layout is nothing but arrangements of elements on the device screen. These elements can be images, tests, videos, anything. They basically define the structure of the Android user interface to make it user friendly.
37. How many layout types are there?
The type of layouts used in Android Apps are as follows:
38. What is an APK?
An APK stands for Android Package that is a file format of Android Applications. Android OS uses this package for the distribution and installation of the Android Application.
39. What is an Android Manifest file?
The manifest file describes all the essential information about the project application for build tools, Android operating system, and google play. This file is a must for every Android project that we develop, and it is present in the root of the project source set.
#android tutorials #android basic interview questions #android basic questions #android developer interview questions #android interview question and answer #android interview questions #android interview questions for experienced #android interview questions for fresher
1617257581
¿Quiere restaurar los buzones de correo de PST a Exchange Server? Entonces, estás en la página correcta. Aquí, lo guiaremos sobre cómo puede restaurar fácilmente mensajes y otros elementos de PST a MS Exchange Server.
Muchas veces, los usuarios necesitan restaurar los elementos de datos de PST en Exchange Server, pero debido a la falta de disponibilidad de una solución confiable, los usuarios no pueden obtener la solución. Háganos saber primero sobre el archivo PST y MS Exchange Server.
PST es un formato de archivo utilizado por MS Outlook, un cliente de correo electrónico de Windows y muy popular entre los usuarios domésticos y comerciales.
Por otro lado, Exchange Server es un poderoso servidor de correo electrónico donde todos los datos se almacenan en un archivo EDB. Los usuarios generalmente guardan la copia de seguridad de los buzones de correo de Exchange en el archivo PST, pero muchas veces, los usuarios deben restaurar los datos del archivo PST en Exchange. Para resolver este problema, estamos aquí con una solución profesional que discutiremos en la siguiente sección de esta publicación.
No le recomendamos que elija una solución al azar para restaurar los datos de PST en Exchange Server. Por lo tanto, al realizar varias investigaciones, estamos aquí con una solución inteligente y conveniente, es decir, Exchange Restore Software. Es demasiado fácil de manejar por todos los usuarios y restaurar cómodamente todos los datos del archivo PST a Exchange Server.
El software es demasiado simple de usar y se puede instalar fácilmente en todas las versiones de Windows. Con unos pocos clics, la herramienta puede restaurar los elementos del buzón de Exchange.
No es necesario que MS Outlook restaure los datos PST en Exchange. Todos los correos electrónicos, contactos, notas, calendarios, etc. se restauran desde el archivo PST a Exchange Server.
Todas las versiones de Outlook son compatibles con la herramienta, como Outlook 2019, 2016, 2013, 2010, 2007, etc. La herramienta proporciona varios filtros mediante los cuales se pueden restaurar los datos deseados desde un archivo PST a Exchange Server. El programa se puede instalar en todas las versiones de Windows como Windows 10, 8.1, 8, 7, XP, Vista, etc.
Descargue la versión de demostración del software de restauración de Exchange y analice el funcionamiento del software restaurando los primeros 50 elementos por carpeta.
No existe una solución manual para restaurar los buzones de correo de Exchange desde el archivo PST. Por lo tanto, hemos explicado una solución fácil e inteligente para restaurar datos de archivos PST en Exchange Server. Simplemente puede usar este software y restaurar todos los datos de PST a Exchange Server.
Más información:- https://www.datavare.com/software/exchange-restore.html
#intercambio de software de restauración #intercambio de restauración #buzón del servidor de intercambio #herramienta de restauración de intercambio
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
1670560264
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.
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.
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