Thierry  Perret

Thierry Perret

1645499493

10 Questions D'entrevue De Réaction Que Vous Devriez Connaître En 2022

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 .

1. Qu'est-ce que Réagir ? Pourquoi l'utiliser ?

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.

  • Cela nous donne un moyen de créer facilement des interfaces utilisateur avec des outils comme JSX
  • Il nous donne des composants pour partager facilement des parties de notre interface utilisateur (UI) , ce que le HTML statique lui-même ne peut pas faire
  • Cela nous permet de créer un comportement réutilisable sur n'importe lequel de nos composants avec des crochets React
  • React s'occupe de mettre à jour notre interface utilisateur lorsque nos données changent, sans avoir besoin de mettre à jour le DOM manuellement nous-mêmes

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.

2. Qu'est-ce que JSX ?

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 divdans 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.

3. Comment transmettez-vous les données aux composants React ?

Il existe 2 manières principales de transmettre des données aux composants React :

  1. Accessoires
  2. API de contexte

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' valueaccessoire à l'aide du Context.Providercomposant. Il peut être consommé à l'aide du composant Context.Consumer ou du useContexthook.

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>
}

4. Quelle est la différence entre l'état et les accessoires ?

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.

5. À quoi servent les fragments React ?

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 Columnscomposant.

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.

6. Pourquoi avons-nous besoin de clés pour les listes React ?

Les clés sont une valeur unique que nous devons transmettre à la keyprop 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 .

7. Qu'est-ce qu'une référence ? Comment l'utilisez-vous?

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 useRefcrochet 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.

8. A quoi sert le hook useEffect ?

Le useEffectcrochet 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.navigatorou document.getElementById().

Nous ne pouvons pas effectuer de telles opérations directement dans le corps de notre composant React. useEffectnous 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.

9. Quand utilisez-vous React Context vs Redux ?

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.

10. A quoi servent les hooks useCallback & useMemo ?

Les crochets useCallbacket useMemoexistent pour améliorer les performances de nos composants.

useCallbackest 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 useMemocrochet, qui diffère du useCallbackcrochet en ce qu'il renvoie une valeur, pas une fonction.

Vous voulez rendre React facile ?

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 :

  • Passez de débutant absolu à professionnel React en seulement 30 minutes par jour
  • Construire 4 projets React complets de zéro au déploiement
  • Découvrez une puissante pile de technologies pour créer n'importe quelle application que vous aimez

Link: https://www.freecodecamp.org/news/react-interview-questions-to-know/

#react 

What is GEEK

Buddha Community

10 Questions D'entrevue De Réaction Que Vous Devriez Connaître En 2022
Thierry  Perret

Thierry Perret

1645499493

10 Questions D'entrevue De Réaction Que Vous Devriez Connaître En 2022

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 .

1. Qu'est-ce que Réagir ? Pourquoi l'utiliser ?

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.

  • Cela nous donne un moyen de créer facilement des interfaces utilisateur avec des outils comme JSX
  • Il nous donne des composants pour partager facilement des parties de notre interface utilisateur (UI) , ce que le HTML statique lui-même ne peut pas faire
  • Cela nous permet de créer un comportement réutilisable sur n'importe lequel de nos composants avec des crochets React
  • React s'occupe de mettre à jour notre interface utilisateur lorsque nos données changent, sans avoir besoin de mettre à jour le DOM manuellement nous-mêmes

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.

2. Qu'est-ce que JSX ?

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 divdans 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.

3. Comment transmettez-vous les données aux composants React ?

Il existe 2 manières principales de transmettre des données aux composants React :

  1. Accessoires
  2. API de contexte

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' valueaccessoire à l'aide du Context.Providercomposant. Il peut être consommé à l'aide du composant Context.Consumer ou du useContexthook.

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>
}

4. Quelle est la différence entre l'état et les accessoires ?

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.

5. À quoi servent les fragments React ?

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 Columnscomposant.

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.

6. Pourquoi avons-nous besoin de clés pour les listes React ?

Les clés sont une valeur unique que nous devons transmettre à la keyprop 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 .

7. Qu'est-ce qu'une référence ? Comment l'utilisez-vous?

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 useRefcrochet 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.

8. A quoi sert le hook useEffect ?

Le useEffectcrochet 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.navigatorou document.getElementById().

Nous ne pouvons pas effectuer de telles opérations directement dans le corps de notre composant React. useEffectnous 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.

9. Quand utilisez-vous React Context vs Redux ?

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.

10. A quoi servent les hooks useCallback & useMemo ?

Les crochets useCallbacket useMemoexistent pour améliorer les performances de nos composants.

useCallbackest 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 useMemocrochet, qui diffère du useCallbackcrochet en ce qu'il renvoie une valeur, pas une fonction.

Vous voulez rendre React facile ?

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 :

  • Passez de débutant absolu à professionnel React en seulement 30 minutes par jour
  • Construire 4 projets React complets de zéro au déploiement
  • Découvrez une puissante pile de technologies pour créer n'importe quelle application que vous aimez

Link: https://www.freecodecamp.org/news/react-interview-questions-to-know/

#react 

Top 130 Android Interview Questions - Crack Technical Interview Now!

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 interview questions

Android Interview Questions – Get ready for 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.

Android Interview Questions for Freshers

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:

  • Android 1.0 – Its release is 23 September 2008.
  • Android 1.1 – Its release date is 9 February 2009.
  • Android 1.5 – Its name is Cupcake, Released on 27 April 2009.
  • Android 1.6 – Its name is Donut, Released on 15 September 2009.
  • Android 2.0 – Its name is Eclair, Released on 26 October 2009
  • Android 2.2 – Its name is Froyo, Released on 20 May 2010.
  • Android 2.3 – Its name is Gingerbread, Released on 06 December 2010.
  • Android 3.0 – Its name is Honeycomb, Released on 22 February 2011.
  • Android 4.0 – Its name is Ice Cream Sandwich, Released on 18 October 2011.
  • Android 4.1 – Its name is Jelly Bean, Released on 9 July 2012.
  • Android 4.4 – Its name is KitKat, Released on 31 October 2013.
  • Android 5.0 – Its name is Lollipop, Released on 12 November 2014.
  • Android 6.0 – Its name is Marshmallow, Released on 5 October 2015.
  • Android 7.0 – Its name is Nougat, Released on 22 August 2016.
  • Android 8.0 – Its name is Oreo, Released on 21 August 2017.
  • Android 9.0 – Its name is Pie, Released on 6 August 2018.
  • Android 10.0 – Its name is Android Q, Released on 3 September 2019.
  • Android 11.0 – As of now, it is Android 11.

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:

  1. Widgets
  2. Intents
  3. Views
  4. Notification
  5. Fragments
  6. Layout XML files
  7. Resources

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.

  1. Single Transactions can only show a single view for the user.
  2. List Fragments have a special list view feature that provides a list from which the user can select one.
  3. Fragment Transactions are helpful for the transition between one fragment to the other.

Frequently asked Android Interview Questions and Answers

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:

  • onCreate()
  • onStart()
  • onPause()
  • onRestart()
  • onResume()
  • onStop()
  • onDestroy()

26. How can you launch an activity in Android?

We launch an activity using Intents. For this we need to use intent as follows:

  1. ntent intent_name= new Intent(this, Activity_name.class);
  2. startActivity(intent_name);

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-

  • onStartCommand()
  • onBind()
  • onCreate()
  • onUnbind()
  • onDestroy()
  • onRebind()

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-

  1. build.xml- It is responsible for the build of Android applications.
  2. bin/ – The bin folder works as a staging area to wrap the files packages into the APK.
  3. src/ – The src is a folder where all the source files of the project are present.
  4. res/ – The res is the resource folder that stores values of the resources that are used in the application. These resources can be colors, styles, strings, dimensions, etc.
  5. assets/ – It provides a facility to include files like text, XML, fonts, music, and video in the Android application.

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-

  1. Multi-tasking
  2. Support for a great range of languages
  3. Support for split-screen
  4. High connectivity with 5G support
  5. Motion Control

34. Why did you learn Android development?

Learning Android Studio is a good idea because of the following-

  1. It has a low application development cost.
  2. It is an open-source platform.
  3. It has multi-platform support as well as Multi-carrier support.
  4. It is open for customizations.
  5. Android is a largely used operating system throughout the world.

35. What are the different ways of storage supported in Android?

The various storage ways supported in Android are as follows:

  1. Shared Preference
  2. Internal Storage
  3. External Storage
  4. SQLite Databases
  5. Network Connection

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:

  1. Linear Layout
  2. Relative Layout
  3. Constraint Layout
  4. Table Layout
  5. Frame Layout
  6. Absolute Layout
  7. Scrollview layout

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

joe biden

1617257581

Software de restauración de Exchange para restaurar sin problemas PST en Exchange Server

¿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.

Conozca PST y 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.

Un método profesional para restaurar PST a Exchange Server

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.

Funciones principales ofrecidas por Exchange Restore Software

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.

Líneas finales

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

How to Create Arrays in Python

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

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


Python Array Tutorial – Define, Index, Methods

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

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

Table of Contents

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

Let's get started!

What are Python Arrays?

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

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

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

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

Lists and arrays behave similarly.

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

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

However, lists and arrays are not the same thing.

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

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

When to Use Python Arrays

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

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

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

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

How to Use Arrays in Python

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

There are three ways you can import the array module:

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

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

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

#how you would create an array
array()

How to Define Arrays in Python

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

The general syntax for creating an array looks like this:

variable_name = array(typecode,[elements])

Let's break it down:

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

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

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

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

import array as arr 

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


print(numbers)

#output

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

Let's break it down:

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

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

import array as arr 

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


print(numbers)

#output

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

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

Another way to create an array is the following:

from array import *

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

print(numbers)

#output

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

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

How to Find the Length of an Array in Python

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

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

import array as arr 

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


print(len(numbers))

#output
# 3

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

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

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

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

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

The general syntax would look something like this:

array_name[index_value_of_item]

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

import array as arr 

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

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

#output

#10
#20
#30

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

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

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

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

import array as arr 

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

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

#30
#20
#10

How to Search Through an Array in Python

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

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

import array as arr 

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

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

#output

#0

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

import array as arr 


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

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

#output

#0

How to Loop through an Array in Python

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

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

import array as arr 

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

print(numbers)

#output

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

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

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

For this you can use a simple for loop:

import array as arr 

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

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

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

import array as arr  

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

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

#output

#10
#20
#30

How to Slice an Array in Python

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

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

import array as arr 

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

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

#output

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

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

import array as arr 

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


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

#output

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

Methods For Performing Operations on Arrays in Python

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

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

How to Change the Value of an Item in an Array

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

import array as arr 

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

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

print(numbers)

#output

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

How to Add a New Value to an Array

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

import array as arr 

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

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

print(numbers)

#output

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

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

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

import array as arr 

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

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

print(numbers)

#output

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

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

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

import array as arr 

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

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

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

print(numbers)

#output

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

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

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

import array as arr 

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

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

numbers.insert(0,40)

print(numbers)

#output

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

How to Remove a Value from an Array

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

import array as arr 

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

numbers.remove(10)

print(numbers)

#output

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

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

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

import array as arr 

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

numbers.remove(10)

print(numbers)

#output

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

Only the first occurence of 10 is removed.

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

import array as arr 

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

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

print(numbers)

#output

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

Conclusion

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

Thanks for reading and happy coding!

#python #programming 

Connor Mills

Connor Mills

1670560264

Understanding Arrays in Python

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

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

Table of Contents

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

Let's get started!


What are Python Arrays?

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

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

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

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

Lists and arrays behave similarly.

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

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

However, lists and arrays are not the same thing.

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

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

When to Use Python Arrays

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

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

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

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

How to Use Arrays in Python

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

There are three ways you can import the array module:

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

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

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

#how you would create an array
array()

How to Define Arrays in Python

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

The general syntax for creating an array looks like this:

variable_name = array(typecode,[elements])

Let's break it down:

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

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

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

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

import array as arr 

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


print(numbers)

#output

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

Let's break it down:

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

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

import array as arr 

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


print(numbers)

#output

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

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

Another way to create an array is the following:

from array import *

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

print(numbers)

#output

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

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

How to Find the Length of an Array in Python

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

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

import array as arr 

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


print(len(numbers))

#output
# 3

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

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

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

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

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

The general syntax would look something like this:

array_name[index_value_of_item]

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

import array as arr 

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

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

#output

#10
#20
#30

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

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

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

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

import array as arr 

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

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

#30
#20
#10

How to Search Through an Array in Python

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

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

import array as arr 

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

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

#output

#0

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

import array as arr 


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

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

#output

#0

How to Loop through an Array in Python

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

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

import array as arr 

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

print(numbers)

#output

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

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

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

For this you can use a simple for loop:

import array as arr 

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

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

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

import array as arr  

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

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

#output

#10
#20
#30

How to Slice an Array in Python

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

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


import array as arr 

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

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

#output

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

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

import array as arr 

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


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

#output

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

Methods For Performing Operations on Arrays in Python

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

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

How to Change the Value of an Item in an Array

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

import array as arr 

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

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

print(numbers)

#output

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

How to Add a New Value to an Array

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

import array as arr 

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

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

print(numbers)

#output

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

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

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

import array as arr 

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

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

print(numbers)

#output

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

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

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

import array as arr 

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

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

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

print(numbers)

#output

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

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

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

import array as arr 

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

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

numbers.insert(0,40)

print(numbers)

#output

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

How to Remove a Value from an Array

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

import array as arr 

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

numbers.remove(10)

print(numbers)

#output

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

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

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


import array as arr 

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

numbers.remove(10)

print(numbers)

#output

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

Only the first occurence of 10 is removed.

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

import array as arr 

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

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

print(numbers)

#output

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

Conclusion

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

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

Thanks for reading and happy coding!

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

#python